[英]Deserializing an array of objects with Json.Net
The received data is like this: 收到的数据是这样的:
Inside each item, there is an object, customer
, I have an identical class for that. 在每个项目中,有一个对象,
customer
,我有一个相同的类。 How can I convert them using Json.net? 如何使用Json.net转换它们?
I have tried the followings: 我试过以下几点:
var data = JsonConvert.DeserializeObject<List<customer>>(val);
and adding another class: 并添加另一个类:
public class customerJson
{
public Customer customer{ get; set; }
}
And trying to deserialize it: 并尝试反序列化它:
var data = JsonConvert.DeserializeObject<List<customerJson>>(val);
With both of them I get an exception: 有了这两个我得到一个例外:
Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[customer]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly.
无法将当前JSON对象(例如{“name”:“value”})反序列化为类型'System.Collections.Generic.List`1 [customer]',因为该类型需要JSON数组(例如[1,2,3] )正确反序列化。 To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object.
要修复此错误,请将JSON更改为JSON数组(例如[1,2,3])或更改反序列化类型,使其成为普通的.NET类型(例如,不是像整数这样的基本类型,而不是类似的集合类型可以从JSON对象反序列化的数组或List。 JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
JsonObjectAttribute也可以添加到类型中以强制它从JSON对象反序列化。 Path 'rows', line 1, position 8.
路径'rows',第1行,第8位。
Data: 数据:
{"rows":[{"id":"232333","name":"nam"},{"id":"3434444","name":"2ndName"}]}
If I read your json data structure correctly you would want this: 如果我正确读取你的json数据结构你会想要这个:
public class Root
{
public List<Customer> rows { get; set; }
}
and 和
var data = JsonConvert.DeserializeObject<Root>(val);
Tested code: 经过测试的代码:
void Main()
{
var test = JsonConvert.DeserializeObject<Root>("{\"rows\":[{\"id\":\"232333\",\"name\":\"nam\"},{\"id\":\"3434444\",\"name\":\"2ndName\"}]}");
Console.WriteLine(test.rows[0].id); // prints 232333
}
public class Customer
{
public int id { get; set; }
}
public class Root
{
public List<Customer> rows { get; set; }
}
Just in case anyone is still having issues. 以防任何人仍有问题。 This worked out for me:
这对我有用:
If the Json looks something like this: 如果Json看起来像这样:
"result": [
{
"firstname": "John",
"lastname": "Doe",
},
{
"firstname": "Max",
"lastname": "Mustermann",
}
]
ResultList.cs ResultList.cs
public class ResultList {
[JsonProperty("result")]
public List<ResultObj> ResultObj { get; set }
}
ResultObj.cs ResultObj.cs
public class ResultObj {
[JsonProperty("firstname")]
public string FirstName { get; set; }
[JsonProperty("lastname")]
public string LastName{ get; set; }
}
And finally: 最后:
using Newtonsoft.Json;
var resultList = JsonConvert.DeserializeObject<ResultList>(jsonString);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.