简体   繁体   中英

How to convert the following JSON array into IDictionary<string, object>?

Following is the serialized JSON array I want to convert to IDictionary

[
  {
    "8475": 25532
  },
  {
    "243": 521
  },
  {
    "3778": 15891
  },
  {
    "3733": 15713
  }
]

When I tried to use

JsonConvert.DeserializeObject<IDictionary<string, object>>((string)jarray);

I got an error saying:

Cannot cast 'jarray' (which has an actual type of 'Newtonsoft.Json.Linq.JArray') to 'string'

The JSON deserializer requires only a string.

If you already have the JArray , all you have to do is convert it to a dictionary I guess.

Roughly something like this:

IDictionary<string,object> dict = jarray.ToDictionary(k=>((JObject)k).Properties().First().Name, v=> v.Values().First().Value<object>());

Check this for complete code with an example

I think there might be a better way to convert it to a dictionary though. I'll keep looking.

the JsonConvert.DeserializeObject<T> Method takes a JSON string , in other words a serialized object.
You have a deserialized object, so you'll have to serialize it first, which is actually pointless, considering you have all the information you need right there in the JArray object. If you are aiming just to get the objects from the array as key value pairs, you can do something like this:

Dictionary<string, object> myDictionary = new Dictionary<string, object>();

foreach (JObject content in jarray.Children<JObject>())
{
    foreach (JProperty prop in content.Properties())
    {
        myDictionary.Add(prop.Name, prop.Value);
    }
}

To turn your JArray into a string, you'll need to assign the key & values of the dictionary for each element. Mario gave a very accurate approach. But there's a somewhat prettier approach as long as you know how to convert each item into your desired type. The below example is for Dictionary<string, string> but can be applied to any Value type.

//Dictionary<string, string>
var dict = jArray.First() //First() is only necessary if embedded in a json object
                 .Cast<JProperty>()
                 .ToDictionary(item => item.Name,
                               item => item.Value.ToString()); //can be modified for your desired type

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