c# - 如何在 newtonsoft JSON 反序列化上接受单个属性的多个名称?

标签 c# json json.net

我们定义了一个标准的 json 格式(拼写错误是故意的):

{
  "Name" : "John",
  "Salari" : "150000"
}

它被反序列化(使用newtonsoft):

class Person
{
    public string Name;
    public string Salari;
}

有没有办法将 Salari 更改为 Salary 并且仍然能够接受旧名称的消息? 像这样的东西:

class Person
{
    public string Name;
    [DeserializeAlso("Salari")]
    public string Salary;
}

为了让 newtonsoft 反序列化器理解 Salari 应该反序列化到 Salary 字段?

最佳答案

您可以利用属性:

class Person
{
  protected string _Salary;
  public string Salary
  {
    get { return _Salary; }
    set { _Salary = value; }
  }
  public string Name { get; set; } 
}

class BackwardCompatiblePerson : Person
{
  public string Salari 
  {
    get { return _Salary; }
    set { _Salary = value; }
  }
}

并使用 Person 进行序列化,使用 BackwardCompatiblePerson 进行反序列化。

关于c# - 如何在 newtonsoft JSON 反序列化上接受单个属性的多个名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30863696/

相关文章:

c# - 在 .NET 中使用 Go CD

Anorm 的 JSON 反序列化器

JavaScript:为什么我的 HTML 中会出现 "quotes"?

php - jQuery 当我选择一个选项来调用函数时

c# - 在 JsonConvert.DeserializeObject 中反序列化对象时出现意外标记

c# - 省略动态属性的类型而不修改类?

c# - Web异常: Unable to connect to the remote server

c# - 高效获取数组子集

c# - 为什么此 AsParallel 操作会抛出数据提供程序错误?

c# - JsonConvert.Deserialize 来自 MVC 操作的 JsonResult