6

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

7

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
3
  • @ChristopherHamkins Json.NET is Newtonsoft. The library is Json.NET and the name of the owner is Newtonsoft, after James Newton-King. Commented Dec 18, 2024 at 14:23
  • OK thanks for the tip, I thought Json.NET is a different package. Commented Dec 19, 2024 at 15:51
  • 1
    This 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. Commented Jul 29 at 18:47

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.