KevinDavis965
KevinDavis965

Reputation: 39

How to convert json array to a dictionary that also contains duplicate keys?

I am trying to convert my json array into key/value pairs in a Dictionary but I keep getting my Keys and Values as null.

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

I am trying to get them as

"Key" : Value
"Key" : Value

Here is the Json

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

I have tried the following

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

Upvotes: 1

Views: 748

Answers (2)

denys-vega
denys-vega

Reputation: 3697

@TheGeneral answer is great. Anyway I wanted to write other version.

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());

Upvotes: 0

TheGeneral
TheGeneral

Reputation: 81503

Given

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; } 

}

To deserialise to a dictionary

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

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

If you have duplicate ids

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);

Upvotes: 1

Related Questions