【问题标题】:Json.NET Convert model to array and return to JObjectJson.NET 将模型转换为数组并返回到 JObject
【发布时间】: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 的问题,如果键值,我希望用数组替换键值存在但还不是数组。

【问题讨论】:

    标签: c# json json.net


    【解决方案1】:

    由于您的密钥可以出现在JObject 中的任何深度,因此您需要使用SelectTokensJsonPath expression 来找到它们。像这样的东西应该可以工作:

    foreach (string item in ValuesToList.ToArray())
    {
        // find all occurrences of the item in the JObject at any depth
        foreach (JToken match in result.SelectTokens("$.." + item))
        {
            // if the matching token is not an array, wrap it in an array
            if (match.Type != JTokenType.Array)
            {
                JProperty parent = (JProperty)match.Parent;
                parent.Value = new JArray(match);
            }
        }
    }
    

    小提琴:https://dotnetfiddle.net/EtDqNs

    【讨论】:

      【解决方案2】:

      你为什么不尝试这样做:

      var arrayProperties = result.DoSomething().OfType<JProperty>().Where(prop => prop.Value.Type == JArray);
      

      【讨论】:

      • 这对于查找属性非常有用,但我需要找到 Key 然后将该键的值转换为数组并将其作为一个整体返回给 JObject。看来这只能找到属性。此外,Value.Type == JArray 在上下文中无效。 (JTokenType.Array) 您能否详细说明这是如何解决转换的?我假设您的意思是 DoSomething() 但如果是这种情况,我仍然无法回答。
      • 看看这个! :) 肯定会helps
      • 如果我对你的问题理解不好,也许this 也会帮助你
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多