0

If I have a simple model like this:

public class Person
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string Age { get; set; }
}

and I have a JSON object like this:

var people = {
    items: [
        { id: "1", name: "j", age: "11"}
    ]
};

and I pass it to a WebMethod like this:

Project.Web.Services.AJAXService.Save(JSON.stringify(people), function (result) {
    //
});

How do I deserialize it at the server so that I can iterate over it with a foreach?

I've tried this:

[WebMethod(true)]
public void Save(string peopleJson)
{
    List<Person> people = JsonConvert.DeserializeObject<List<Person>>(peopleJson);

    foreach (var person in people)
    {
        string str = person.Name;
    }
}

But it throws the following Exception:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Project.Data.Models.Person]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly

edit: I just found out from this question that it in fact isn't JSON but JavaScript object literal notation, but I still want to be able to parse what I have here.

edit2: This is the content of peopleJson: "{\"items\":[{\"id\":\"1\",\"name\":\"j\",\"age\":\"11\"}]}"

Community
  • 1
  • 1
notAnonymousAnymore
  • 2,637
  • 9
  • 49
  • 74

2 Answers2

1

Use this class to deserialize

JsonConvert.DeserializeObject<Root>(peopleJson);

public class Root
{
    public List<Person> items { get; set; }
}
L.B
  • 114,136
  • 19
  • 178
  • 224
1

Problem is in items wrapper. It should be

JsonConvert.DeserializeObject<ListOfPersons>(peopleJson)

where

public class ListOfPersons
{
  public Person[] Items {get; set;}
}
Dima
  • 6,721
  • 4
  • 24
  • 43