简体   繁体   中英

Iterating over a JSON object on the server-side

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 (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[Project.Data.Models.Person]' because the type requires a JSON array (eg [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\\"}]}"

Use this class to deserialize

JsonConvert.DeserializeObject<Root>(peopleJson);

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

Problem is in items wrapper. It should be

JsonConvert.DeserializeObject<ListOfPersons>(peopleJson)

where

public class ListOfPersons
{
  public Person[] Items {get; set;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM