c# - 使用 Json.Net 反序列化对象数组

标签 c# json json.net

接收到的数据是这样的:

enter image description here

在每个项目中,都有一个对象,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/

相关文章:

c# - 如何跟踪调用的每个方法

javascript - 如何将 Geodjango 与 Google Maps API 3 集成?

c# - 如何从 JsonDocument 中提取具有指定名称的所有 JsonProperty 对象的所有值?

android - 编码来自 JSON (äöüß) 的特殊字符

c# - 使用属性属性来定义要使用的 JsonConverter

c# - 登录后将用户重定向回原始操作

c# - 在.net/c#中调用Marketo Rest Api的示例代码

c# - 将 JSON 反序列化为对象时出现问题

c# - 我想在没有双引号的情况下为现有的 Json 添加值

c# - Dapper 和用户定义的数据库类型