简体   繁体   中英

How to deserialize json property for enumeration class using Json.Net?

I am trying to avoid using Enums and use enumeration classes instead such as explained here https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/enumeration-classes-over-enum-types

Now I have the following example

public class Dto
{
public string Name {get;set;}
public StatusType Status {get;set;}
}

public class StatusType : Enumeration
{
public static readonly StatusType Active = new StatusType (1, "Active");
public static readonly StatusType Inactive = new StatusType (2, "Inactive");
}

When I try to deserialize Dto such as

var message = JsonConvert.DeserializeObject<Dto>(test);

I get an error 'Error converting value "Active" to type 'StatusType'.

Is it possible to use or create a converter that would actually convert value "Active" to a proper StatusType?

You will need to write custom JsonConverter . For example like this:

public class StatusTypeConverter : JsonConverter<StatusType>
{
    // can be build with reflection 
    private static Dictionary<string, StatusType> _map = new Dictionary<string, StatusType>(StringComparer.InvariantCultureIgnoreCase)
    {
        {StatusType.Active.Name, StatusType.Active},
        {StatusType.Inactive.Name, StatusType.Inactive}
    };
    public override void WriteJson(JsonWriter writer, StatusType value, JsonSerializer serializer)
    {
        writer.WriteValue(value.Name);
    }

    public override StatusType ReadJson(JsonReader reader, Type objectType, StatusType existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        string s = (string)reader.Value;

        return _map[s];
    }
}

public class Dto
{
    public string Name { get; set; }
    [JsonConverter(typeof(StatusTypeConverter))]
    public StatusType Status { get; set; }
}

var js = "{'name': 'Name', 'status': 'active'}";
Console.WriteLine(JsonConvert.DeserializeObject<Dto>(js).Status.Name); // prints "Active"

This code obviously can be improved(meaningful exception for missing keys, building converter which can handle all subtypes of Enumeration with help of reflection).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM