I currently have a class say (that looks like this)
public class foo
{
public MyEnumType Result { get; set; };
}
currently when I do this
foo a = new foo();
string str = JsonConvert.SerializeObject(a);
The Result comes out as int type. Is there a way for me to get it as string type ? by telling it to do MyEnumTypeInstance.toString();
asked Sep 22, 2019 at 1:44
1 Answer 1
JSON.Net has a built-in converter, the StringEnumConverter
, you just add an attribute to the property you are [de]serialising, for example:
[JsonConverter(typeof(StringEnumConverter))]
public MyEnumType Result { get; set; }
Or specify the converter during serialisation:
string str = JsonConvert.SerializeObject(a, new StringEnumConverter());
answered Sep 22, 2019 at 1:51
-
@ChristopherHamkins Json.NET is Newtonsoft. The library is Json.NET and the name of the owner is Newtonsoft, after James Newton-King.DavidG– DavidG12/18/2024 14:23:22Commented Dec 18, 2024 at 14:23
-
OK thanks for the tip, I thought Json.NET is a different package.Christopher Hamkins– Christopher Hamkins12/19/2024 15:51:59Commented Dec 19, 2024 at 15:51
-
1This comment is not true (But was at one time I think) Json.Net nuget.org/packages/Json.Net Newtonsoft.Json nuget.org/packages/newtonsoft.json They have a couple subtle differences that can cause issues if you are not paying attention to wich one you are using.MikeF– MikeF07/29/2025 18:47:12Commented Jul 29 at 18:47
lang-cs