Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON array to C# Dictionary

Tags:

json

c#

json.net

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.

like image 617
bbsimonbb Avatar asked Dec 02 '22 13:12

bbsimonbb


2 Answers

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);
like image 62
Przemek Marcinkiewicz Avatar answered Dec 24 '22 17:12

Przemek Marcinkiewicz


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()
like image 35
Chris Avatar answered Dec 24 '22 18:12

Chris