使用自定义JsonConverter反序列化接口列表? - c#

我在json文件中有一个List<ISomething>,但找不到一种简单的方法
反序列化而不使用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 },
    ]
}

在这种情况下,ShapesList<IShape>,其中IShape是具有这两个实现程序的接口:
ShapeRectShapeDxf

我已经创建了一个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;

如何将此JsonConverter应用于列表?

谢谢。

参考方案

在您的课程中,您可以使用JsonProperty属性标记列表,并使用ItemConverterType参数指定转换器:

class Foo
{
    public Size Size { get; set; }

    [JsonProperty(ItemConverterType = typeof(MyConverter))]        
    public List<IShape> Shapes { get; set; }
}

或者,您可以将转换器的实例传递给JsonConvert.DeserializeObject,前提是您已实现CanConvert,以便在objectType == typeof(IShape)时返回true。然后,Json.Net会将转换器应用于列表中的项目。

JSON.NET如何删除节点 - c#

我有一个像下面这样的json:{ "d": { "results": [ { "__metadata": { }, "prop1": "value1", "prop2": "value2", "__some&#…

JSON PATH字段NULL检查表达式 - java

我有一个像bellow的json数组:{ "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sa…

json_encode的特定方式 - php

所以这是我的PHP<?php include 'connect.php'; $sql = "SELECT name from startup_schema"; $result = mysqli_query($mysqli, $sql) or die("Error in Selecting " …

json_encode网址失败 - php

有人在this bug附近吗?echo json_encode(array('url'=>'/foo/bar')); {"url":"\/foo\/bar"} 我使用Zend_Json and Zend_Json_Expr以便我甚至可以在js对象中获取回调函数-但我无法获得…

如何从JSON文件反序列化.NET Core中封装的对象表? - c#

我想从外部API检索足球联赛的集合。来自服务器的响应如下所示:{ "api": { "results": 1496, "leagues": [ { "league_id": 1, ..... 返回的对象由“ api”字段组成,其中包含“结果”和“联盟”。我想反序列化代码并将其映射…