1

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); 
3
  • You should first serialize it to array of objects and then you can convert to dictionary by selecting which property to be used as key and which to be used as value. Commented Jul 10, 2020 at 2:40
  • What is supposed to be the key and what's the value? Commented Jul 10, 2020 at 2:52
  • Your json is just a regular array Commented Jul 10, 2020 at 7:37

2 Answers 2

1

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); 
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

This will throw for duplicate keys.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.