首页 > 解决方案 > 将 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。

我搜索类似的问题,但找不到解决方案。问候

标签: c#jsonjson-deserialization

解决方案


按照您现在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"
        }
    ]
}

推荐阅读