0

I'm trying to populate a JSON/XML string into C# object. I convert my XML to JSON and then use JSON.NET. Example:

JSON string

{  
"persons":[  
  {  
     "age":30,
     "name":"david",
     "hobbies":[  
        {  
           "name":"tennis",
           "hours":5
        },
        {  
           "name":"football",
           "hours":10
        }
     ]
  },
  {  
     "name":"adam",
     "age":23,
     "hobbies":[]
  }
]
}

C# Classes

public class Hobbies
{
    public string name;
    public int hours;
}

class Person
{
    public string name;
    public int age;
    public List<Hobbies> hoobies = new List<Hobbies>();
}

I'm trying to populate the data into a list of persons:

List<Person> persons = new List<Person>();
JsonConvert.PopulateObject(myJsonText, persons);

and I'm getting this exception:

Cannot populate JSON object onto type

How can I do that?

2 Answers 2

3

Here is JSON representation of an Object:

{
  "key":"value"
}

and here is the representation of a collection/array/list of an Object

[
    {
      "key":"value"
    },
    {
      "key2":"value2"
    }
]

So your JSON string doesn't representing the array or collection of the Person class. It's representing the object with Persons property which is a collection of Person object.

To parse it to the List<Person>, remove the outermost { } and then try.

Your JSON should look like this

[
    {
        "age": 30,
        "name": "david",
        "hobbies": [
            {
                "name": "tennis",
                "hours": 5
            },
            {
                "name": "football",
                "hours": 10
            }
        ]
    },
    {
        "name": "adam",
        "age": 23,
        "hobbies": []
    }
]

and then deserialize it like this

var result = JsonConvert.DeserializeObject<List<Person>>(json);
Sign up to request clarification or add additional context in comments.

Comments

2

You need a root object

public class Root
{
    public List<Person> Persons {set;get;}
}

Now you can deserialize

var yourObj = JsonConvert.DeserializeObject<Root>(json);

Comments

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.