2
   {
       "id":"123", "result":
       {
           "0": { "children_id": "0", "name": "some name" },
           "1": { "children_id": "1", "name": "some other name" }
        }
    }

I have this pice of JSON string, how i can deserialize it using: JSON.NET http://json.codeplex.com ?

I was trying make some class which can hold my json object, but i i don't know how i can hold this "0" and "1".

public class Data
{
    public string children_id  { get; set; }
    public string name { get; set; }
}

public class RootObject
{
    public string id { get; set; }
    public List<Data> result { get; set; }
}
1
  • Are you looking for this? new System.Web.Script.Serialization. JavaScriptSerializer().Deserialize(string) ? Commented Jun 21, 2013 at 17:19

3 Answers 3

6

This JSON looks badly designed. If you can have multiple children, it should be an array, such as:

{
   "id":"123", "result":
   [
       { "children_id": "0", "name": "some name" },
       { "children_id": "1", "name": "some other name" }
   ]
}

If you have control over the JSON generation, change that (your current C# code would work in deserialization). If you don't, you are better off deserializing that to a dictionary, which would make your RootObject look like this:

public class RootObject
{
    public string id { get; set; }
    public Dictionary<int, Data> result { get; set; }
}
Sign up to request clarification or add additional context in comments.

2 Comments

It would be much easier, but i get from one API such JSON string... Using this json online parser: json.parser.online.fr my example json is parasing like in result field is array. It's no way to parse it in easy way?
@Yozer Then, try the Dictionary solution.
1
public class Data
{
    public string id { get; set; }
    public string name { get; set; }
}

public class RootObject
{
    public string id { get; set; }
    public Dictionary<string, Data> result { get; set; }
}

1 Comment

Answers containing just code with no explanation are not very useful.
-1
JObject jObject = new JObject();
/* jObject = {
   "id":"123", "result":
   {
       "0": { "children_id": "0", "name": "some name" },
       "1": { "children_id": "1", "name": "some other name" }
    }
}
*/
foreach(var g in jObject["result"]){
   switch(g.Key()){
     case 0://do something
            break;
   }
}

1 Comment

I don't understand what are you trying to say with this answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.