接收到的数据是这样的:
在每个项目中,都有一个对象,customer
,我有一个相同的类。如何使用 Json.net 转换它们?
我尝试了以下方法:
var data = JsonConvert.DeserializeObject<List<customer>>(val);
并添加另一个类:
public class customerJson
{
public Customer customer{ get; set; }
}
并尝试反序列化它:
var data = JsonConvert.DeserializeObject<List<customerJson>>(val);
对于他们两个我都有一个异常(exception):
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[customer]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'rows', line 1, position 8.
数据:
{"rows":[{"id":"232333","name":"nam"},{"id":"3434444","name":"2ndName"}]}
最佳答案
如果我正确阅读了你的 json 数据结构,你会想要这样:
public class Root
{
public List<Customer> rows { get; set; }
}
和
var data = JsonConvert.DeserializeObject<Root>(val);
测试代码:
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; }
}
关于c# - 使用 Json.Net 反序列化对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31176933/