将属性映射到对象列表

时间:2017-08-16 21:34:51

标签: c# .net json json.net

我有一个如下所示的JSON数据:

{
    "Item1": {
        "Field1": "Val1",
        "Field2": "Val2"
    },
    "Item2": {
        "Field1": "Val11",
        "Field2": "Val22"
    }
}

我需要将它反序列化为一组看起来像这样的类:

public class Root
{
    public List<Item> Items; // << Item1 and Item2 should go here
}

public class Item
{
    public string Field1;
    public string Field2;
}

如何在反序列化时使Newtonsoft.Json以这种方式映射数据?

4 个答案:

答案 0 :(得分:7)

如果您需要从JSON中的相同数据填充Items列表 Item类中显示的各个Root属性,那么您为此需要一个自定义的JsonConverter。以下转换器应工作:

public class RootConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Root);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject obj = JObject.Load(reader);
        var root = new Root();

        // populate all known Root properties 
        serializer.Populate(obj.CreateReader(), root);

        // populate Items list with all objects that can be converted to an Item
        root.Items = obj.Properties()
                        .Where(p => p.Value.Type == JTokenType.Object && 
                                    (p.Value["Field1"] != null || p.Value["Field2"] != null))
                        .Select(p => p.Value.ToObject<Item>())
                        .ToList();
        return root;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

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

然后使用它,将[JsonConverter]属性添加到您的Root类中,如下所示:

[JsonConverter(typeof(RootConverter))]
public class Root
{
    public Item Item1 { get; set; }
    public Item Item2 { get; set; }

    public List<Item> Items; // << all the Items should go here
}

提琴:https://dotnetfiddle.net/aADhzw

答案 1 :(得分:3)

不需要课程 Root 。我会反序列化为词典

window.addEventListener('mousedown', (e) => {
  e.preventDefault()
}, true);

答案 2 :(得分:2)

来自@ L.B帖子:如果您需要使用Root对象,可以尝试以下方法:

public class Root : Dictionary<string, Item>
{
    public List<Item> Items => this.Values.ToList();
}

然后您可以将JSON反序列化为Root对象:

 var root = JsonConvert.DeserializeObject<Root>(json);

答案 3 :(得分:-1)

使用:

public class Root
{
    public List<Item> Items {get;set;}
}
public class Item
{
    public string Field1 {get;set;}
    public string Field2; {get;set;}
}

作为课程,并致电:

Root foobar = new JavaScriptSerializer().Deserialize<Root>(result);

反序列化。