Reputation: 1697
I have a class contains an enum property and using newtonsoft.json serilaizer I am serializing an instance of it . I want the output of serializing this property to be the string value of the property,so I used StringEnumConverter but the output was like this
** without converter : "FailOrPassProperty":1
** with converter : "FailOrPassProperty":"1"
So using the converter it seems like it is getting the ToString() of the integer
I have tried this solution but it didn't work: JSON serialization of enum as string
Note: I cannot use attribute decoration due to business rules.
Upvotes: 2
Views: 3208
Reputation: 14084
check this out :
[TestClass]
public class JsonStringTest
{
[TestMethod]
public void EnumToStringSerializationTest()
{
var testMe = new TestMe()
{
UserType = UserType.User,
};
var settings = new JsonSerializerSettings();
settings.Converters.Add(new StringEnumConverter());
var jsonString = JsonConvert.SerializeObject(testMe, settings);
Assert.AreEqual(jsonString, "{\"UserType\":\"User\"}");
}
}
public class TestMe
{
public UserType UserType { get; set; }
}
public enum UserType
{
Admin = 1,
User = 2
}
Update :
Just wanted to add this note :
make sure that your enum items doesn't have EnumMember
Attribute because the StringEnumConverter
will use this value instead of the enum item name.
Upvotes: 1