【发布时间】:2017-05-12 13:24:32
【问题描述】:
我无法找到 JObject 嵌套键以便将键值转换为数组。下面的代码似乎只获取父键而不是整个对象。
我想要什么:将JObject 中的任何ValuesToList 项目转换为JArray,如果它们还不是一个数组,不管键的嵌套程度如何。注意:解决方案应该适用于完全不同的 Json 模型。
目的:有时 Json 作为模型而不是数组返回,这会导致反序列化到模型引发异常。
result = {{ "errors": null, "content": { "officeId": 1, "daysClosed": [] } }}
// values in ValuesToList are "content" and "daysClosed"
var result = JObject.Parse(_responseString);
foreach (string item in ValuesToList.ToArray())
{
// Check to see if toList value is contained in the JObject.
if (result[item] != null)
{
// Check to see if the value is an array. If not, will convert to array/list Json.
if (!(result[item] is JArray))
result[item] = new JArray(result[item]);
}
}
问题是我在JObject 中找不到daysClosed,因为它是一个孩子。因此,当item = "daysClosed" result[item] 将返回null。
我正在研究一种使用反射来解决这个问题的方法,但遇到了一个新的JObject 将被附加到当前JObject 的问题,如果键值,我希望用数组替换键值存在但还不是数组。
【问题讨论】: