如何处理可以是两种不同类型之一的 json 字段?

How to handle a json field, which can be one of two different types?

我正在为 MSCOCO annotation format.

创建模型 classes

'ObjectDetection'中有一个字段,可以是以下两种类型之一:

annotation{
    "id": int, 
    "image_id": int, 
    "category_id": int, 
    "segmentation": RLE or [polygon], 
    "area": float, 
    "bbox": [x,y,width,height], 
    "iscrowd": 0 or 1,
}

所以 segmentation 可以是 List<List<float>>RunLenghtEncoding,class 看起来像这样

public class RunLengthEncoding
{
    [JsonProperty("size")]
    public List<int>? Size { get; set; }

    [JsonProperty("counts")]
    public List<int>? Counts { get; set; }
}

问题是,转换json时如何处理这种情况?通常我会创建一个抽象 class 并从中继承我的两种不同类型。可以在自定义转换器中选择正确的具体类型。

但是,使用此配置,这似乎是不可能的。我也不想使用 object.

如果未来的读者有兴趣,我现在是这样解决的:

在我的注释模型中 class 我有这三个分割属性:

[JsonProperty("segmentation")]
public JToken? Segmentation { get; set; }

[JsonIgnore]
public List<List<float>>? Polygons { get; set; }

[JsonIgnore]
public RunLengthEncoding? RLE { get; set; }

然后我使用 OnDeserialized 回调将分段映射到正确的 属性。在我的例子中,这非常简单,因为根据 MSCOCO 文档,当 IsCrowd 为真时使用 RLE,否则使用多边形:

[OnDeserialized]
internal void OnDeserialized(StreamingContext context)
{
    if (Segmentation == null)
        return;

    if(IsCrowd)
    {
        RLE = Segmentation.ToObject<RunLengthEncoding>();
    }
    else
    {
        Polygons = Segmentation.ToObject<List<List<float>>>();
    }
}

再次感谢@Heinzi 的建议!