Tes*_*esX 4 .net c# json json.net
我List<ISomething>在json文件中有一个,并且找不到不使用反序列化的简单方法TypeNameHandling.All
(我不希望/不能使用,因为JSON文件是手写的)。
有没有一种方法可以将属性[JsonConverter(typeof(MyConverter))]应用于列表的成员,而不是应用于列表?
{
"Size": { "Width": 100, "Height": 50 },
"Shapes": [
{ "Width": 10, "Height": 10 },
{ "Path": "foo.bar" },
{ "Width": 5, "Height": 2.5 },
{ "Width": 4, "Height": 3 },
]
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,Shapes是一个List<IShape>其中IShape与这两种实现者的接口:
ShapeRect与ShapeDxf。
我已经创建了一个JsonConverter子类,该子类将该项目作为JObject加载,然后根据给定的属性是否存在来检查要加载的实际类Path:
var jsonObject = JObject.Load(reader);
bool isCustom = jsonObject
.Properties()
.Any(x => x.Name == "Path");
IShape sh;
if(isCustom)
{
sh = new ShapeDxf();
}
else
{
sh = new ShapeRect();
}
serializer.Populate(jsonObject.CreateReader(), sh);
return sh;
Run Code Online (Sandbox Code Playgroud)
如何将此JsonConverter应用于列表?
谢谢。
在您的课程中,您可以使用JsonProperty属性标记列表,并使用以下ItemConverterType参数指定转换器:
class Foo
{
public Size Size { get; set; }
[JsonProperty(ItemConverterType = typeof(MyConverter))]
public List<IShape> Shapes { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
另外,您可以将转换器的实例传递给JsonConvert.DeserializeObject,前提是您已实现CanConvert,当时返回true objectType == typeof(IShape)。然后,Json.Net会将转换器应用于列表中的项目。