MistyD
MistyD

Reputation: 17223

How to tell NewtonSoft.Json.JsonConvert to serialize an enum to a string and not an int

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

Upvotes: 5

Views: 2009

Answers (1)

DavidG
DavidG

Reputation: 118937

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

Upvotes: 5

Related Questions