【发布时间】:2020-01-27 21:36:38
【问题描述】:
我收到一个像
这样的 json 对象 {
"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 数组反序列化的 List。 JsonArrayAttribute 也可以添加到类型中以强制它 从 JSON 数组反序列化。路径'',第 1 行,位置 1。'
我搜索了类似的问题,但找不到解决方案。问候
【问题讨论】:
-
JsonConvert.DeserializeObject<DesignAssignViewModel[]>或者如果您想要JsonConvert.DeserializeObject<DesignViewModel>,请确保您的 json 字符串具有对象格式,该格式具有包含DesignViewModel对象数组的属性DesignAssignList。 -
在你的 json 中创建对象数组并按照@RezaAghaei 所说的去做。
-
@RezaAghaei 这不是很有帮助。
-
@user1538301 如我所见,您的 json 未形成为数组。您应该添加 [ ] 像 [{"prop1":""},{"prop2":""}]
-
您的 json 无效.....您需要有效的 json。到jsonlint.com 并在那里发布你的 json 以确保它是有效的
标签: c# json json-deserialization