How to convert the following JSON array to IDictionary <string, object>?
Below is a serialized JSON array that 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:
Cannot write 'jarray' (which has the actual type 'Newtonsoft.Json.Linq.JArray') for 'string'
A JSON deserializer only needs a string.
+4
2 answers
If you already have one JArray, all you have to do is convert it into a dictionary, which I think.
Like that:
IDictionary<string,object> dict = jarray.ToDictionary(k=>((JObject)k).Properties().First().Name, v=> v.Values().First().Value<object>());
Check this out for complete code with an example.
I think there may be a better way to convert it to a dictionary. I will continue to search.
+6