反序列化其中的值与JSON.NET字段名的JSON [英] Deserialize the JSON where the values are field names with JSON.NET

查看:158
本文介绍了反序列化其中的值与JSON.NET字段名的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求我反序列化其中的值与JSON.NET字段名的JSON非常不理想的情况。假设我有以下的JSON,这是非常正确的结构:

I have a very undesirable situation which requires me to deserialize the JSON where the values are field names with JSON.NET. Assuming that I have the following JSON which is very properly structured:

{
    "name": "tugberk",
    "roles": [
        { "id": "1", "name": "admin" },
        { "id": "2", "name": "guest" }
    ]
}

这很容易与JSON.NET反序列化这CLR对象:

It's very easy to deserialize this with JSON.NET to a CLR object:

class Program
{
    static void Main(string[] args)
    {
        var camelCaseSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };

        var text = File.ReadAllText("user_normal.txt");
        var obj = JsonConvert.DeserializeObject<User>(text, camelCaseSettings);
    }
}

public class User
{
    public string Name { get; set; }
    public Role[] Roles { get; set; }
}

public class Role
{
    public int Id { get; set; }
    public string Name { get; set; }
}

不过,以我现在的情况,我有以下的可怕JSON相当于上述JSON在价值观方面:

However, in my current case, I have the following horrible JSON which is equivalent to above JSON in terms of values:

{
    "name": "tugberk",
    "roles": {
        "1": { "name": "admin" },
        "2": { "name": "guest" }
    }
}

正如你所看到的,角色字段不是一个数组;它是一个对象,它包含其他值对象与它的独特的键作为自己的字段名(这是可怕的)。什么是反序列化这个JSON以上用户类JSON.NET最好的方法是什么?

As you can see, roles field is not an array; it's an object which contains other values as objects with it's unique keys as their field names (which is horrible). What's the best way to deserialize this JSON to above User class with JSON.NET?

推荐答案

您可以创建自定义 JsonConverter 该序列化/反序列化角色[] 。然后,您可以装饰你的角色与财产 JsonConverterAttribute 是这样的:

You can create a custom JsonConverter which serializes/deserializes Role[]. You can then decorate your Roles property with the JsonConverterAttribute like this:

public class User
{
    public string Name { get; set; }
    [JsonConverter(typeof(RolesConverter))]
    public Role[] Roles { get; set; }
}

在你的转换器类,你可以阅读的对象,并返回一个数组来代替。你的转换器类可能是这样的:

In your converter class you are able to read an object and return an array instead. Your converter class may look like this:

class RolesConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Role[]);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // deserialize as object
        var roles = serializer.Deserialize<JObject>(reader);
        var result = new List<Role>();

        // create an array out of the properties
        foreach (JProperty property in roles.Properties())
        {
            var role = property.Value.ToObject<Role>();
            role.Id = int.Parse(property.Name);
            result.Add(role);
        }

        return result.ToArray();
    }


    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

这篇关于反序列化其中的值与JSON.NET字段名的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆