c# - 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);
我能够获得“详细信息”,但不能获得对象内的列表。
解决方案
你需要使用一个对象来包含你的 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 格式。
推荐阅读
- node.js - Socket.io 优化:socket.io 是否发送 JSON 字符串?我们如何优化它?
- html - 占宽度 100% 的复选框
- java - gcj 错误 - 找不到类 java.util.function.Predicate 的文件
- vue.js - 如果孩子在vue中有课程,如何设置父母的样式?
- vba - 使用标准复制和粘贴值 vba
- html - 变暗的图像问题css
- vue.js - Vue.js 从问题中导入
- android - 如何从android studio中的txt文件中检索字符串?
- vba - 在Excel VBA中以不同的顺序输入选择单元格
- vue.js - 子视图组件将道具传递给Vue中的父布局