我有一个JSON数组,其中包含具有不同属性的不同类型的对象.其中一个属性称为"类型",并确定数组项的类型.以下是我的数据示例:

   [{
        type : "comment",
        text : "xxxx"
    }, {
        type : "code",
        tokens : [{
                type : "ref",
                data : "m"
            }, {
                type : "operator",
                data : "e"
            }
        ]
    }, {
        type : "for",
        boundLocal : {
            type : "local",
            name : "i",
            kind : "Number"
        },
        upperBound : {
            type : "ref",
            tokens : [{
                    type : "operator",
                    data : "3"
                }, {
                    type : "operator",
                    data : "0"
                }
            ]
        },
        body : [{
                type : "code",
                tokens : [{
                        type : "ref",
                        data : "x"
                    }
                ]
            }, {
                type : "code",
                tokens : [{
                        type : "ref",
                        data : "y"
                    }
                }
                ]
        ]
    ]

To map those objects to my .Net implementation I define a set of classes: one base class and several child classes (with a complex hierarchy, having 4 "generations"). Here is just a small example of these classes:

public abstract class TExpression
{
    [JsonProperty("type")]
    public string Type { get; set; }
}

public class TComment : TExpression
{
    [JsonProperty("text")]
    public string Text { get; set; }
}   

public class TTokenSequence : TExpression
{
    [JsonProperty("tokens")]
    public List<TToken> Tokens { get; set; }
}

What I want to reach is to be able to deserialize this array into a covariant generic list, declared as:

List<TExpression> myexpressions = JsonConvert.DeserializeObject<List<TExpression>>(aststring);

This list should contain the instances of appropriate child classes inheriting from TExpression, so I can use the following code later in my code:

foreach(TExpression t in myexpressions)
{
    if (t is TComment) dosomething;
    if (t is TTokenSequence) dosomethingelse;
}

如何使用JSON访问它.网

推荐答案

下面是一个使用CustomCreationConverter的示例

public class JsonItemConverter :  Newtonsoft.Json.Converters.CustomCreationConverter<Item>
{
    public override Item Create(Type objectType)
    {
        throw new NotImplementedException();
    }

    public Item Create(Type objectType, JObject jObject)
    {
        var type = (string)jObject.Property("valueType");
        switch (type)
        {
            case "int":
                return new IntItem();
            case "string":
                return new StringItem();
        }

        throw new ApplicationException(String.Format("The given vehicle type {0} is not supported!", type));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Load JObject from stream
        JObject jObject = JObject.Load(reader);

        // Create target object based on JObject
        var target = Create(objectType, jObject);

        // Populate the object properties
        serializer.Populate(jObject.CreateReader(), target);

        return target;
    }
}

public abstract class Item
{
    public string ValueType { get; set; }

    [JsonProperty("valueTypeId")]
    public int ValueTypeId { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    public new virtual string ToString() { return "Base object, we dont' want base created ValueType=" + this.ValueType + "; " + "name: " + Name; }
}

public class StringItem : Item
{
    [JsonProperty("value")]
    public string Value { get; set; }

    [JsonProperty("numberChars")]
    public int NumberCharacters { get; set; }

    public override string ToString() { return "StringItem object ValueType=" + this.ValueType + ", Value=" + this.Value + "; " + "Num Chars= " + NumberCharacters; }

}

public class IntItem : Item
{
    [JsonProperty("value")]
    public int Value { get; set; }

    public override string ToString() { return "IntItem object ValueType=" + this.ValueType + ", Value=" + this.Value; }
}

class Program
{
    static void Main(string[] args)
    {
        // json string
        var json = "[{\"value\":5,\"valueType\":\"int\",\"valueTypeId\":1,\"name\":\"numberOfDups\"},{\"value\":\"some thing\",\"valueType\":\"string\",\"valueTypeId\":1,\"name\":\"a\",\"numberChars\":11},{\"value\":2,\"valueType\":\"int\",\"valueTypeId\":2,\"name\":\"b\"}]";

        // The above is deserialized into a list of Items, instead of a hetrogenous list of
        // IntItem and StringItem
        var result = JsonConvert.DeserializeObject<List<Item>>(json, new JsonItemConverter());

        foreach (var r in result)
        {
            // r is an instance of Item not StringItem or IntItem
            Console.WriteLine("got " + r.ToString());
        }
    }
}

Json相关问答推荐

如何使用GoFr返回XML响应?

使用PowerShell解析文件并获取特定行的值

Jolt-Json转换:通过引用标识符(而不是索引)设置值

Powershell v7 文本背景突出显示

golang递归json来构造?

通过 xslt 将内部 json 转换为 xml 时遇到问题

如何实现一个通用的 serde_json::from_str

我无法在 Go - Gin 中解析日期/时间

SwiftUI:如何使用 0 索引数组键为 JSON 添加类型

Swift:如何从字典中删除空值?

读取 HttpwebResponse json 响应,C#

使用 API 搜索维基百科

Spring Security 和 JSON 身份验证

如何使用 Newtonsoft.Json 包在 C#(4.0) 中解析我的 json 字符串?

杰克逊:反序列化 for each 值都具有正确类型的 Map

杰克逊在通用列表中读取 json

从 JSON 到 JSONL 的 Python 转换

JSON - 是否有任何 XML CDATA 类似功能?

从动态 json 数据更新力有向图上的链接

无法解析 JSON 文件中的 TAB