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();

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());
Sign up to request clarification or add additional context in comments.

3 Comments

@ChristopherHamkins Json.NET is Newtonsoft. The library is Json.NET and the name of the owner is Newtonsoft, after James Newton-King.
OK thanks for the tip, I thought Json.NET is a different package.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.