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\"}]}"