[英]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: 我有一个像这样的JSON
对象:
var people = {
items: [
{ id: "1", name: "j", age: "11"}
]
};
and I pass it to a WebMethod
like this: 我将它传递给WebMethod
如下所示:
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
? 如何在服务器上反序列化它以便我可以使用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
: 但它抛出以下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 无法将当前JSON对象(例如{“name”:“value”})反序列化为类型'System.Collections.Generic.List`1 [Project.Data.Models.Person]',因为该类型需要JSON数组(例如[ 1,2,3])正确反序列化
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. 编辑:我刚从这个问题中发现它实际上不是JSON
而是JavaScript
对象文字表示法,但我仍然希望能够解析我在这里的内容。
edit2: This is the content of peopleJson
: "{\\"items\\":[{\\"id\\":\\"1\\",\\"name\\":\\"j\\",\\"age\\":\\"11\\"}]}"
edit2:这是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. 问题在于items
包装。 It should be 它应该是
JsonConvert.DeserializeObject<ListOfPersons>(peopleJson)
where 哪里
public class ListOfPersons
{
public Person[] Items {get; set;}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.