【问题标题】:How to convert json array to a dictionary that also contains duplicate keys?如何将 json 数组转换为包含重复键的字典?
【发布时间】:2020-07-10 02:36:00
【问题描述】:

我正在尝试将我的 json 数组转换为字典中的键/值对,但我的键和值一直为空。

Exception : System.ArgumentNullException: 'Value cannot be null.
Parameter name: key'

我试图让他们成为

"Key" : Value
"Key" : Value

这是 Json

[
  {
    "id": 1,
    "name": "David",
    "type": 0
  },
  {
    "id": 12,
    "name": "John",
    "type": 0,
  }
]

我已经尝试了以下

var value = JsonConvert.DeserializeObject<List<KeyValuePair<string, object>>>(jsonString).ToDictionary(x => x.Key, y => y.Value);

【问题讨论】:

  • 您应该首先将其序列化为对象数组,然后您可以通过选择哪个属性用作键和哪个属性用作值来转换为字典。
  • 什么应该是关键,什么是价值?
  • 你的json只是一个普通数组

标签: c# arrays json api


【解决方案1】:

给定

public class MyArray    {
    public int id { get; set; } 
    public string name { get; set; } 
    public int type { get; set; } 

}

public class SomeFunkyRoot    {
    public List<MyArray> MyArray { get; set; } 

}

反序列化为字典

var root = JsonConvert.DeserializeObject<SomeFunkyRoot>(jsonString);

// returns Dictionary<int,MyArray>
var dict root.MyArray
             .ToDictionary(x => x.id);

如果您有重复的 ID

var root = JsonConvert.DeserializeObject<SomeFunkyRoot>(jsonString);

// returns Dictionary<int,List<MyArray>>
var dict = root.MyArray
              .GroupBy(x => x.id)
              .ToDictionary(x => x.Key, x => x.ToList());

// or you could use a lookup
// returns ILookup<int,MyArray>
var lookup = root.MyArray
                 .ToLookup(x => x.id);

【讨论】:

    【解决方案2】:

    @TheGeneral 答案很棒。反正我想写别的版本。

    var anonymousType = new[] { new { id = 0, name = "", type = 0 } };
    var data = JsonConvert.DeserializeAnonymousType(json, anonymousType);
    var dict = data.GroupBy(x => x.id).ToDictionary(x => x.Key, x => x.ToList());
    

    【讨论】:

    • 这会抛出重复的键。
    猜你喜欢
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多