首页 > 解决方案 > RestSharp JsonDeserializer 列表对象

问题描述

我想使用 RestSharp 反序列化反序列化带有数组的 JSON。

public class details
{
    public string id { get; set; }
    public string tran_id { get; set; }
    public string tran_type { get; set; }
    public string tran_status { get; set; }
    public string expiry_date_time { get; set; }
    public string number { get; set; }
}

我的JSON如下:

{
"details": [
    {
        "id": "ebca66079b44",
        "tran_id": "c9b1bce025f5",
        "tran_type": "A",
        "tran_status": "B",
        "expiry_date_time": "2018-11-26T06:33:04+00:00",
        "number": "12345678ABC"
    },
    {
        "id": "ebca66079b44",7c2445c8-a5ba-4ad2-a38e-3ea682c60edf",
        "tran_id": "3ea682c60edf",
        "tran_type": "A",
        "tran_status": "B",
        "expiry_date_time": "2018-11-26T06:26:28+00:00",
        "number": "22345678ABC"
    },
    {
        "id": "ebca66079b44",
        "tran_id": "e40c45817985",
        "tran_type": "A",
        "tran_status": "B",
        "expiry_date_time": "2018-11-26T06:26:06+00:00",
        "number": "32345678ABC"
    }
]
}

我的代码是:

IRestResponse response = client.Execute(request);
//Deserialize Json
return new JsonDeserializer().Deserialize<List<details>>(response);

我能够获得“详细信息”,但不能获得对象内的列表。

标签: c#restsharpjson-deserialization

解决方案


你需要使用一个对象来包含你的 JSON 数组数据,因为最外层是一个对象而不是一个数组。

public class JsonModel
{
    public List<Detail> details { get; set; }
}


public class Detail
{
    public string id { get; set; }
    public string tran_id { get; set; }
    public string tran_type { get; set; }
    public string tran_status { get; set; }
    public string expiry_date_time { get; set; }
    public string number { get; set; }
}

像这样使用。

new JsonDeserializer().Deserialize<JsonModel>(response);

笔记

有一个 json 数据可能会从"ebca66079b44",7c2445c8-a5ba-4ad2-a38e-3ea682c60edf",数据中抛出一个错误。

有两种方法可以轻松创建模型。

  • 您可以在 Visual Studio 中使用 Web Essentials,使用 Edit > Paste special > paste JSON as a class,您可以更容易地了解 Json 和模型之间的关系。

  • 如果您不能使用 Web Essentials,您可以使用https://app.quicktype.io/?l=csharp online JSON to Model 类来代替。

您可以尝试使用这些模型来承载您的 JSON 格式。


推荐阅读