【问题标题】:Custom JSON serialization/deserialization to read property in multiple possible formats自定义 JSON 序列化/反序列化以读取多种可能格式的属性
【发布时间】:2019-12-10 14:07:00
【问题描述】:

我的应用程序读取使用如下格式创建的 JSON 文件:

{
  "myProperty": {complex JSON here}
}
class MyClass
{
   public MyChildClass MyProperty {get; set;}
}

我需要更改课程的工作方式,使其看起来像这样:

class MyClass
{
   public MyNewChildClass MyNewProperty {get; set;}
}

而且我需要能够支持以旧格式创建的文件,但也支持使用新格式创建的文件。

我有将MyChildClass 对象转换为MyNewChildClass 对象的代码,但是如何设置序列化以便对象可以反序列化旧格式,将属性名称和类型从MyChildClass MyProperty 更改为MyNewChildClass MyNewProperty 并且在序列化和反序列化时只使用新格式,如果 JSON 文件包含这种格式,则使用新格式?

【问题讨论】:

  • 添加两个属性....如果缺少属性。它将被设置为空值

标签: c# json json.net


【解决方案1】:

如果您同时使用这两个属性,则 json 将适用于新旧两种属性。

class MyClass
{
   [JsonPropert("myProperty")]
   public MyChildClass MyProperty {get; set;}

   [JsonProperty("myNewProperty")] // -> Remember, case matters.
   public MyNewChildClass MyNewProperty {get; set;}
}

当你反序列化类时,添加一个检查以查看哪个不为空并使用它(我猜每种方法都不同)。这应该可以帮助您将重大更改保持在最低限度。

顺便说一句>。如果您有将新旧转换为旧的代码,反之亦然,您可以检查旧的值是否为空,然后运行您必须将新转换为旧的过程/方法并继续使用该对象。请记住,它必须在反序列化之后,

var properties = JsonConvert.DeserializeObject<MyClass>("data");
if (properties.MyNewProperty == null) 
{
   properties = myMethodToConvertOldToNew(properties);
}

public MyClass myMethodToConvertOldToNew(MyClass)
{
  if (properties.New == null)
  {
     properties.New = ConversionMethod(properties.Old, properties.New);
     // dont have to, but,
     properties.Old = null;
  }
  return properties.

}

【讨论】:

    【解决方案2】:

    为什么不向你的类添加一个私有属性来设置你的新属性:

    class MyClass
    {
       [JsonProperty]
       private MyChildClass MyProperty { set => MyNewProperty = YourConversionMethod(value); }
    
       public MyNewChildClass MyNewProperty { get; set; }
    }
    

    JsonProperty 属性将确保使用私有设置器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 2017-04-06
      • 1970-01-01
      • 2017-11-15
      • 2014-08-02
      • 2022-09-23
      • 1970-01-01
      相关资源
      最近更新 更多