c# - 将 JSON 反序列化为 c# 模型
问题描述
我收到一个像
{
"designKey": 7470,
"title": "Test1",
"note": "Test1",
"createdBy": "username",
"creationDate": "2020-01-24T20:47:28.297" },
{
"designKey": 7472,
"title": "Test2",
"note": "Test2",
"createdBy": "username",
"creationDate": "2020-01-24T23:20:44.207" },
{
"designKey": 7473,
"title": "Test3",
"note": "Test3",
"createdBy": "username",
"creationDate": "2020-01-24T23:39:03.99" }
所以我创建模型来反序列化,如:
public class AssignDesignModel
{
public class DesignViewModel
{
public IList<DesignAssignViewModel> DesignAssignList { get; set; } = new List<DesignAssignViewModel>();
}
public class DesignAssignViewModel
{
public int DesignKey { get; set; }
public string Title { get; set; }
public string Note { get; set; }
public string CreatedBy { get; set; }
public DateTime CreationDate { get; set; }
}
}
我执行为:
var rModel = JsonConvert.DeserializeObject<DesignViewModel>(response.content);
但它抛出了一个异常:
Newtonsoft.Json.JsonSerializationException:'无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'Project.Models.AssignDesignModel+DesignViewModel',因为该类型需要 JSON 对象(例如 {"name":"value "}) 正确反序列化。要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList),例如可以从 JSON 数组反序列化。JsonArrayAttribute 也可以添加到类型中以强制它从 JSON 数组反序列化。路径'',第 1 行,位置 1。
我搜索类似的问题,但找不到解决方案。问候
解决方案
按照您现在DesignViewModel
定义的方式,您的 JSON 必须如下所示:
{
"DesignAssignList": [
{
"designKey": 7470,
"title": "Test1",
"note": "Test1",
"createdBy": "username",
"creationDate": "2020-01-24T20:47:28.297"
},
{
"designKey": 7472,
"title": "Test2",
"note": "Test2",
"createdBy": "username",
"creationDate": "2020-01-24T23:20:44.207"
},
{
"designKey": 7473,
"title": "Test3",
"note": "Test3",
"createdBy": "username",
"creationDate": "2020-01-24T23:39:03.99"
}
]
}
推荐阅读
- reactjs - 使用 react-table 从其他外部组件获取 state.filters 数组
- ios - 启动 facebook 事件 URL 导致“Safari 无法打开页面,因为地址无效”
- javascript - python中的jQuery
- jenkins - 管道中凭证的 Jenkins Groovy 错误
- material-ui - 有没有办法混淆 material-ui 类名?
- recursion - 具有递归调用的函数的时间复杂度,该递归调用将 N 除以另一个取决于 N 的数字
- reactjs - TypeError:无法读取未定义的属性(读取“toLowerCase”)
- javascript - 使用NodeJS(公共应用程序)时如何在shopify中获取当前商店?
- c# - 不支持连接字符串关键字“服务器”
- gitlab - 如何使用工件压缩整个 laravel 发布的文件夹?