System.Text.Json: How to serialize a individual enum as number when the json configuration has a general JsonStringEnumConverter

Viewed 2241

System.Text.Json default to number the enum serialization. In my case I need the string for that in the Startup.cs I add a converter to get all the enum serializing to string as is show here.

 .AddJsonOptions(
           c =>
           {
             c.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
          }
        );

but I have a particular enum that I need to serialize to number.

public enum fareStatus
{
    None = 0,
    Club = 1,
    NoClub = 2
}

In this case I want to get 0,1,2 and not the string,

is that possible in this scenario? Thanks

1 Answers

if you want to get just number from enum try this

    var item = new Item { Status = fareStatus.NoClub };
    var options = new JsonSerializerOptions();
    var json= JsonSerializer.Serialize(item,options);

json

{"Status":2}

and try this code

    var options = new JsonSerializerOptions();
    options.Converters.Add(new JsonStringEnumConverter());
    var json= JsonSerializer.Serialize(item,options);

    item=JsonSerializer.Deserialize<Item>(json,options);

json

{"Status":"NoClub"}

class

public class Item
{
    public fareStatus Status {get; set;}
}
Related