反序列化json中的private设置不正确

问题描述

正如您所见,我有这个课程:

public class UserScope
    {
        public List<Guid> testCenterIds { get; private set; }
        public List<Guid> roleIds { get; private set; }
        public List<int> townCodes { get; private set; }
        public List<int> CityCodes { get; private set; }
        public List<int> provinceCodes { get; private set; }
        public List<string> provinceCodes2 { get; private set; }

        public UserScope(List<Guid> testCenterIds,List<Guid> roleIds,List<int> townIds,List<int> cityIds,List<int> provinceIds,List<string> provinceIds2)
        {
            this.testCenterIds = testCenterIds;
            this.roleIds = roleIds;
            this.townCodes = townIds;
            this.CityCodes = cityIds;
            this.provinceCodes = provinceIds;
            this.provinceCodes2 = provinceIds2;
        }
    }

当我想将json转换为模型时,您会看到:

  static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        var uc = new UserScope(
   new List<Guid> { Guid.NewGuid(),Guid.NewGuid() },new List<Guid> { Guid.NewGuid(),new List<int> { 12126 },new List<int> { 12122 },new List<int> { 12312,13479 },new List<string> { "12312","13479" }

  );
        var jsons = Newtonsoft.Json.JsonConvert.SerializeObject(uc);

        var jsond = Newtonsoft.Json.JsonConvert.DeserializeObject<UserScope>(jsons);
    }

JsonConvert无法转换townCodes,CityCodes,provinceCodes,provinceCodes2并对其进行初始化,最后townCodes,provinceCodes2为null。但是testCenterIds,roleIds可以正常工作。为什么?

解决方法

您的UserScope只有一个接受某些参数的构造函数(没有参数的默认构造函数),并且没有属性用JsonProperty标记,因此JSON.NET假定它需要将该构造函数调用为创建一个实例。然后,它将json字符串中的键与该构造函数的参数名称进行匹配。 testCenterIdsroleIds名称确实与所述键匹配,而其他参数名称不匹配,因此JSON.NET在那里传递null。如果您这样重命名构造函数参数:

public UserScope(List<Guid> testCenterIds,List<Guid> roleIds,List<int> townCodes,List<int> cityCodes,List<int> provinceCodes,List<string> provinceCodes2)
{
    this.testCenterIds = testCenterIds;
    this.roleIds = roleIds;
    this.townCodes = townCodes;
    this.CityCodes = cityCodes;
    this.provinceCodes = provinceCodes;
    this.provinceCodes2 = provinceCodes2;
}

然后将它们全部填充。另外,您也可以使用注释中链接的答案中提到的JsonProperty属性标记所有属性(如果可能和合适的话,最好总是这样做)。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...