当我序列化我的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属性?
我可能会感到困惑,''Type“:4,'与你所说的'$ type'有什么不同,你所引用的'$ type'的位置和方式在哪里?你可以添加“所需”的输出,使其更加明显吗?我可能只是不看同一件事... –
您的代码对于独立序列化工作正常,请参阅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
@dbc我正在使用.NET Core WebAPI。我的问题已经更新了该代码。我尝试在列表中添加'[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Auto)]',并且我为通用列表获得了'$ type',但不是列表中的控件。 – Targaryen