【问题标题】:serializing/deserializing derived objects using JSON.NET without using JsonProperty?使用 JSON.NET 序列化/反序列化派生对象而不使用 JsonProperty?
【发布时间】:2011-06-06 03:20:24
【问题描述】:

我正在使用 NewtonSoft JSON.NET 库来序列化以下 DTOBase 可以保存派生实例的类。

public class Command
{         
    public DTOBase CommandDTO  { get; set; }                
}

根据this article,您需要包含 JsonProperty 属性,以便正确反序列化派生实例

public class Command
{ 

  [JsonProperty(TypeNameHandling = TypeNameHandling.All)]  
  public DTOBase CommandDTO  { get; set; }       
 }

问题是除了使用属性是否还有其他方法可以获得相同的结果?我宁愿不耦合到 NewtonSoft 库和 json 序列化,特别是在类级别。有没有办法在库的 Serialize/Deserialize 方法上指定一些设置以获得相同的结果?

【问题讨论】:

    标签: json.net


    【解决方案1】:

    当您调用JsonConvert.SerializeObject(value, settings) 时,可以在JsonSerializerSettings 上设置TypeNameHandling 属性。

    如果您只希望包含派生对象的名称,请将TypeNameHandling 设置为TypeNameHandling.Auto

    【讨论】:

    • 嗨,James,我试过了,但没有用,序列化的字符串不包含属性的类型信息,就像我使用 JsonProperty 属性时那样。 v var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All}; string serializedInstance = JsonConvert.SerializeObject(myobject,Formatting.None,settings);
    • 看起来我有一个旧版本的 te 库。我升级到了最新版本,带有 TypeNameHandling.Auto 的 JsonSerializerSettings 按预期工作。
    猜你喜欢
    • 1970-01-01
    • 2012-12-18
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多