5

I've successfully deserialized this JSON string in C#, but can't extract the values from the objects nested in the array:

JavaScriptSerializer js = new JavaScriptSerializer();

string json = 
  {"key":"1234","status":"ok","members":
      [{"id":7,"name":"Joe"},
   {"id":2,"name":"Robert"},
   {"id":18,"name":"Tim"}
      ]
   }

var d = js.Deserialize < dynamic > (json);

string _key = d["key"]; // this works

Array _members = d["members"]; // this works, length = 3

But I'm having trouble extracting the values out of the objects by name, e.g, this isn't right, but essentially I want

_members[0]["name"] or, _members[0].name

I think the deserializer makes the objects inside the array dictionaries, but I think I'm clearing missing something...

2
  • checkout the following links..stackoverflow.com/questions/7482822/…, json.org Commented Mar 2, 2012 at 0:34
  • The KeyValuePair iteration looks promising, but I can't get down into the {} objects to use it. Commented Mar 2, 2012 at 0:59

3 Answers 3

18

I recommend using Json.NET to do what you're doing. The following code does what you want:

    JObject jObject = JObject.Parse(json);
    JToken memberName = jObject["members"].First["name"];
    Console.WriteLine(memberName); // Joe

Via LINQ to Json.

Update:

    var js = new JavaScriptSerializer();
    var d = js.Deserialize<dynamic>(json);
    Console.WriteLine(d["members"][0]["name"]); // Joe

Also works fine.

Sign up to request clarification or add additional context in comments.

1 Comment

I had a similar issue. Your answer helped. Thank you
4

It's a bit late for an answer but I've been trying to figure this out and thought I should post somewhere what worked for me.

I wanted to use foreach so:

foreach (var member in json["members"])
    {
        Console.WriteLine(member["name"]);
    }

and by the way, (for some reason like in my project) if you have nested arrays, e.g.

string json = 
{"key":"1234","status":"ok",
 "members":[
   {"items"[
       {"id":7,"name":"Joe"},
       {"id":2,"name":"Robert"},
       {"id":18,"name":"Tim"}
   ]}
]}

Then:

foreach (var member in json["members"])
    {
        foreach (var item in member["items"])
        {  
            Console.WriteLine(item["name"]);
        }
    }

Comments

2

You were quite close in syntax. The key here is that d["members"] is of type Object[] / object[]. Instead of Array, you can use dynamic[] and everything works just fine.

Also note that even this declaration isn't explicitly necessary, as shown in DPeden's updated sample.

Here is the code for your updated snippet (I used a console app to test):

JavaScriptSerializer js = new JavaScriptSerializer();
dynamic d = js.Deserialize<dynamic>(json);

string key = d["key"];
string status = d["status"];
dynamic[] members = d["members"];

Console.WriteLine("key = {0}", key);
Console.WriteLine("status = {0}", status);

Console.WriteLine("members.length = {0}", members.Length);
Console.WriteLine("members type name = {0}", members.GetType().Name);
Console.WriteLine("d[\"members\"] type name = {0}", d["members"].GetType().Name);

And here is additional code showing array and member access.

Console.WriteLine("--");

for (int i = 0; i < members.Length; i++)
{
    Console.WriteLine("members[{0}][\"id\"] = {1}", i, members[i]["id"]);
    Console.WriteLine("members[{0}][\"name\"] = {1}", i, members[i]["name"]);
}

Console.WriteLine("--");

Console.WriteLine("{0}", d["members"][0]["id"]);
Console.WriteLine("{0}", d["members"][0]["name"]);

Console.ReadKey();

3 Comments

How would you get the string value for members[i]["name"]?
if there is any chance name is null, then you would have to do: object o = d["members"][i]["name"]; string name = null == o ? null : (string)o;, but otherwise, (string)(d["members"][i]["name"]) works
Thanks, I ended up getting Convert.ToString(bla) to work. Thanks for the reply!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.