Reese Reese - 4 months ago 68
JSON Question

c# - Convert JSON to array

I'm using Newtonsoft JSON.

Newtonsoft.Json.Linq.JArray userLists = Newtonsoft.Json.Linq.JArray.Parse(result)
MessageBox.Show((string)userLists[0]["name"]);


"result" contains:


{"response":"1","0":{"id":"1","username":"bla","name":"bla
"},"1":{"id":"2","username":"blub","name":"blub"}}


What's wrong? The messagebox is empty and at index 1 it throws an error.
Thanks in advance.

Answer

Your JSON does not contain an array but rather an object. You can access it via the string index:

var o = JObject.Parse("{'response':'1','0':{'id':'1','username':'bla','name':'bla '},'1':{'id':'2','username':'blub','name':'blub'}}");
MessageBox.Show((string)o["0"]["name"]);
Comments