Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON StringEnumConverter Not Working

Tags:

json

c#

enums

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.

like image 532
Bakri Bitar Avatar asked May 07 '26 14:05

Bakri Bitar


1 Answers

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.

for more information

like image 56
Wahid Bitar Avatar answered May 10 '26 02:05

Wahid Bitar