5

How do I convert a JSON array like this

[{"myKey":"myValue"},
{"anotherKey":"anotherValue"}]

to a C# Dictionary with json.net or system classes.

json.net can serialize directly to a dictionary, but only if you feed it an object, not an array.

bbsimonbb
  • 27,056
  • 15
  • 80
  • 110
  • Possible duplicate of [How can I deserialize JSON to a simple Dictionary in ASP.NET?](http://stackoverflow.com/questions/1207731/how-can-i-deserialize-json-to-a-simple-dictionarystring-string-in-asp-net) – Andrey Korneyev Apr 28 '17 at 09:00
  • 3
    Not a duplicate. My JSON is an array. That's a constraint. – bbsimonbb Apr 28 '17 at 09:03
  • But it does look like a duplicate of [Newtonsoft JSON.NET parse to array of custom key/value pair objects](https://stackoverflow.com/q/33552322/3744182), agree? – dbc Jun 25 '21 at 06:42

6 Answers6

8

Maybe converting to array of KeyValuePairs will help

using System.Linq;

var list = JsonConvert.DeserializeObject<IEnumerable<KeyValuePair<string, string>>>(jsonContent);
var dictionary = list.ToDictionary(x => x.Key, x => x.Value);
bbsimonbb
  • 27,056
  • 15
  • 80
  • 110
Przemek Marcinkiewicz
  • 1,267
  • 1
  • 19
  • 32
  • 8
    Did this actually work for you? I got the correct number of kvps but they had null keys and values. I think it is because Json.Net can't construct them with the Create() method. I ended up having to use a list of single element dictionaries. – Ryan May 17 '18 at 13:19
  • This doesn't seem to work. An `IEnumerable>` will serialize as `[{"Key":"myKey","Value":"myValue"},{"Key":"anotherKey","Value":"anotherValue"}]` not `[{"myKey":"myValue"},{"anotherKey":"anotherValue"}]`. See: https://dotnetfiddle.net/ChfYuV. – dbc Jun 25 '21 at 05:56
6

For anyone interested - this works, too:

Example JSON:

[{"device_id":"VC2","command":6,"command_args":"test args10"}, {"device_id":"VC2","command":3,"command_args":"test args9"}]

C#:

JsonConvert.DeserializeObject<List<JObject>>(json)
            .Select(x => x?.ToObject<Dictionary<string, string>>())
            .ToList()
Chris
  • 835
  • 12
  • 27
5

Its quite simple actually :

lets say you get your json in a string like :

string jsonString = @"[{"myKey":"myValue"},
{"anotherKey":"anotherValue"}]";

then you can deserialize it using JSON.NET as follows:

JArray a = JArray.Parse(jsonString);

// dictionary hold the key-value pairs now
Dictionary<string, string> dict = new Dictionary<string, string>();

foreach (JObject o in a.Children<JObject>())
{
    foreach (JProperty p in o.Properties())
    {
        string name = p.Name;
        string value = (string)p.Value;
        dict.Add(name,value);
    }
}
pix
  • 1,264
  • 19
  • 32
Digvijay
  • 774
  • 5
  • 10
3

I found that using a list of KeyValuePairs didn't work. I got the right number of elements but they had null Keys and Values.

In the end the only solution that worked for me was deserialising to a list of dictionaries (which each had a single kvp element).

Ryan
  • 2,109
  • 1
  • 15
  • 19
0

The data must to be sent as follows (format):

"Values": [
  {"Key" : "abc"  , "Value": 23.14},
  {"Key" : "abc1" , "Value": 23.11},
  {"Key" : "abc2" , "Value": 23.17},
  {"Key" : "abc3" , "Value": 23.19}
]

thereby, the converting process will work. It worked fine to me in my attempt to convert from JSON to dictionary<string,decimal>

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
Jordan
  • 19
  • 1
  • 2
0

Since you can only deserialize from an object, do just that by manipulating the JSON string a little first. Wrap it in an object:

json = String.Format("{{\"result\":{0}}}", json);