【发布时间】:2017-11-08 16:25:38
【问题描述】:
我有一个这样的类层次结构:
class Rule { }
class Condition { List<Rule> Rules { get; set; } }
忘记其余的属性。我需要使用自定义 JsonConverter 从 JSON 字符串反序列化。问题是,我有每个特定案例的代码,但我不能让它递归运行,为了照顾 Rules 属性,它的每个元素也可以是一个 Condition。 我的代码是这样的(ReadJson 方法):
var jo = JObject.Load(reader);
Rule rule = null;
if (jo["condition"] == null)
{
rule = new Rule();
//fill the properties for rule
}
else
{
rule = new Condition();
//I now want the converter to go through all the values in jo["rules"] and turn them into Rules or Conditions
}
实现这一目标的最佳方法是什么?如果发现该对象是一个条件,我尝试获取其余部分的 JSON:
var json = jo.GetValue("rule").ToString();
但是我不能像这样反序列化它,它会抛出一个异常:
var rules = JsonConvert.DeserializeObject<Rule[]>(json, this);
异常是:JsonReaderException:从 JsonReader 读取 JObject 时出错。当前 JsonReader 项不是对象:StartArray。路径'',第 1 行,位置 1。
有什么想法吗?
【问题讨论】:
-
JSON 是什么样的?
-
当然,就像一组规则或可能的条件。像 [ { ... }, { "condition": true, ... } ]
标签: json.net json-deserialization