Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

c#

json.net

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.

like image 914
Saurabh Avatar asked Sep 24 '14 12:09

Saurabh


3 Answers

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.

like image 144
Conrad Clark Avatar answered Oct 19 '22 09:10

Conrad Clark


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);
    }
}
like image 2
Mario Stoilov Avatar answered Oct 19 '22 09:10

Mario Stoilov


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
like image 1
Daniel Avatar answered Oct 19 '22 09:10

Daniel