I’m developing an application that reads some JSON data and makes some statistics, but now I’ve run into a problem.
I have a string like this:
{
"position":[
{
"someKey1":"someVal1",
"someKey2":"someVal2",
},
{
"someKey1":"someVal3",
"someKey2":"someVal4",
}
}
I want to access the someKeys and someValues.
I’m converting it to a dictionary like this:
Dictionary<string, object> values = deserializeJSON(json_string);
Edit 1: Sorry, forgot to add deserializeJSON:
private Dictionary<string, object> deserializeJSON(string p_jsonObject)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Deserialize<Dictionary<string, dynamic>>(p_jsonObject);
}
Now I have trouble getting access to the list of values with the key “position”. If I try to print the type of values[“position”] I get:
System.Collections.ArrayList
So I thought I could just iterate through this, but I can’t. I tried using enumerator (read in here that it would make it possible to iterate over the objects, and that I have to add it to an ArrayList to cast it):
ArrayList arr = new ArrayList();
IEnumerable enumerable = values["position"] as IEnumerable;
foreach (object element in enumerable)
{
arr.Add(element);
}
When I print arr[0] I get:
System.Collections.Generic.Dictionary`2[System.String,System.Object]
Here I’m confused. I assume it’s the list of someKeys and someVals, which should be correct, right?
Now I’ve tried, with no luck, getting access to these values. I tried arr[0][“someKey1”] but get an error that I cannot apply indexing to ‘object’.
Any ideas on a solution? Ideally a more elegant solution? 🙂
Thanks in advance
You can use Linq to JSON (add Newtonsoft’s JSON.NET from NuGet):
Another sample: