【发布时间】:2012-01-04 16:45:07
【问题描述】:
我有一个 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"
}
}
]
]
]
为了将这些对象映射到我的 .Net 实现,我定义了一组类:一个基类和几个子类(具有复杂的层次结构,具有 4 个“代”)。这里只是这些类的一个小例子:
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; }
}
我想要达到的是能够将这个数组反序列化为一个协变的泛型列表,声明为:
List<TExpression> myexpressions = JsonConvert.DeserializeObject<List<TExpression>>(aststring);
此列表应包含从 TExpression 继承的适当子类的实例,因此我可以稍后在我的代码中使用以下代码:
foreach(TExpression t in myexpressions)
{
if (t is TComment) dosomething;
if (t is TTokenSequence) dosomethingelse;
}
如何使用 JSON.NET 访问它?
【问题讨论】:
标签: c# json json.net deserialization