Home > Blockchain >  Trying to convert enum to custom string name with JsonStringEnumConverter
Trying to convert enum to custom string name with JsonStringEnumConverter

Time:06-16

I was trying represent some use-case scenario like below. I have json formatted data. And it include an enum class. They send this enum class with int type. I want to show this enum value with a meaningful string. But I couldn't make it.

How can I show this EnumMember custom value?

Edit: I want to show "Not Hot" value. Not Hot_Not enum.

static void Main(string[] args) {
    var jsonString = "{\"Summary\":\"40\"}";
    var options = new JsonSerializerOptions {
        Converters = {
            new JsonStringEnumConverter()
        }
    };
    WeatherForecastWithEnum ? weatherForecast = JsonSerializer.Deserialize < WeatherForecastWithEnum > (jsonString, options) !;
    Console.WriteLine(weatherForecast.Summary);
}

public class WeatherForecastWithEnum {
    public Summary ? Summary {
        get;
        set;
    }
}

public enum Summary {
    Cold = 30,
    Cool = 10,
    Warm = 20,
    [EnumMember(Value = "Not Hot")]
    Hot_Not = 40
}

CodePudding user response:

By default, it is not supported with System.Text.Json . You can see the request for the same.

https://github.com/dotnet/runtime/issues/31081

But there is an extension library called 'Macross.Json.Extensions' where you can use JsonStringEnumMemberConverter attribute and then do what you need.

JsonConverter(typeof(JsonStringEnumMemberConverter))]
public enum DefinitionType
{
   [EnumMember(Value = "UNKNOWN_DEFINITION_000")]
   DefinitionUnknown
}

     [TestMethod]
    public void ExampleTest()
    {
        string Json =  JonSerializer.Serialize(DefinitionType.DefinitionUnknown);

        Assert.AreEqual("\"UNKNOWN_DEFINITION_000\"", Json);

        DefinitionType ParsedDefinitionType =    JsonSerializer.Deserialize<DefinitionType>(Json);

         Assert.AreEqual(DefinitionType.DefinitionUnknown, ParsedDefinitionType);
   }

You can see more at - https://github.com/Macross-Software/core/tree/develop/ClassLibraries/Macross.Json.Extensions#enumerations

  • Related