简体   繁体   中英

JSON array to C# Dictionary

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.

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

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

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

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

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM