2017-04-14 85 views
1

当我序列化我的Page对象时,Json.Net没有在我的Controls(它们在IList)中添加$ type属性,当它将它们序列化时。我曾尝试将下面的代码添加到我的类构造函数和我的WebAPI启动中,但Json.Net仍然没有将$ type信息添加到它序列化的Control

 JsonConvert.DefaultSettings =() => new JsonSerializerSettings 
     { 
      TypeNameHandling = TypeNameHandling.All, 
      MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead 
     }; 

出于测试目的,我在JSON代码添加$type属性来控制自己,Json.Net能够反序列化正确的对象,但它仍然是不正确的序列化。以下是我的课程设置。

public class Page { 
    public Guid Id { get; set; } 
    public Guid CustomerId { get; set; } 
    public IList<Control> Controls { get; set; } 
} 

这里是控制类:

public class Control : ControlBase 
{ 
    public override Enums.CsControlType CsControlType { get { return Enums.CsControlType.Base; } } 
} 

这里是ControlBase抽象类:

public abstract class ControlBase 
{ 
    public Guid Id { get; set; } 

    public virtual Enums.CsControlType CsControlType { get; } 

    public Enums.ControlType Type { get; set; } 

    public string PropertyName { get; set; } 

    public IList<int> Width { get; set; } 

    public string FriendlyName { get; set; } 

    public string Description { get; set; } 
} 

而这里是从控制导出的OptionsControl:

public class OptionsControl : Control 
{ 
    public override Enums.CsControlType CsControlType { get { return Enums.CsControlType.OptionsControl; } } 

    public IDictionary<string, string> Options; 
} 

而这是JSON怎么弄出来:

"Pages": [ 
    { 
     "Id": "00000000-0000-0000-0000-000000000000", 
     "CustomerId": "00000000-0000-0000-0000-000000000000", 
     "Controls": [ 
     { 
      "Options": { 
      "TN": "TN" 
      }, 
      "CsControlType": 4, 
      "Id": "00000000-0000-0000-0000-000000000000", 
      "Type": 4, 
      "PropertyName": "addresses[0].state", 
      "Width": [ 
      2, 
      2, 
      6 
      ], 
      "FriendlyName": "State", 
      "Description": null 
     } 
     ] 
    } 
] 

正如你所看到的,Json.Net未在$type属性添加到JSON对象。问题是,有时我需要Json.Net给我一个基地Control对象,但有时我需要它给我一个OptionsControl对象(它继承自Control)的实例。为什么Json.Net不向我的控件添加$ type属性?

+0

我可能会感到困惑,''Type“:4,'与你所说的'$ type'有什么不同,你所引用的'$ type'的位置和方式在哪里?你可以添加“所需”的输出,使其更加明显吗?我可能只是不看同一件事... –

+0

您的代码对于独立序列化工作正常,请参阅https://dotnetfiddle.net/gKetpA。因此,您必须使用一些框架(如web api)来序列化。你在用什么框架?例如,对于MVC 4 Web API,请参阅[如何在MVC 4 Web API中为Json.NET设置自定义JsonSerializerSettings](https://stackoverflow.com/q/13274625/3744182)。或者,你可以添加'[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Auto)]'到你的列表属性。 – dbc

+0

@dbc我正在使用.NET Core WebAPI。我的问题已经更新了该代码。我尝试在列表中添加'[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Auto)]',并且我为通用列表获得了'$ type',但不是列表中的控件。 – Targaryen

回答

1

而不是修改你的框架使用的全局设置,您可以添加[JsonProperty(ItemTypeNameHandling = TypeNameHandling.All)]public IList<Control> Controls { get; set; }财产强制类型信息发出对列表中的每个项目:

public class Page 
{ 
    public Guid Id { get; set; } 
    public Guid CustomerId { get; set; } 
    [JsonProperty(ItemTypeNameHandling = TypeNameHandling.All)] 
    public IList<Control> Controls { get; set; } 
} 

样品fiddle

由于here解释的原因,您可能会考虑使用定制序列化联编程序清理类型信息。