【问题标题】:How do I loop over this JObject?我如何循环这个 JObject?
【发布时间】:2021-03-26 02:07:01
【问题描述】:

我能够读取 json 文件并将其存储在 JObject 变量中。我需要检查空值并忽略任何具有空值的段。我正在考虑循环遍历 JObject,但我不知道如何访问下面 json 中的每个段/键。

我认为我们可以根据我在这里看到的另一个问题像这样循环:

 foreach (var x in example) //example is the JObject in which json file is stored
    {
        string name = x.Key;
        JToken value = x.Value;

    }

但我的 json 没有密钥。我如何进入每个细分市场并检查名称、描述值是否不为空?

我的 json 是:

{
  "lorem ipsum Segment Groups":[
    {
      "name":"lorem ipsum",
      "description":"lorem ipsum",
      "segments":[
        "Not Enrolled",
        "Started Enrollment – Zipcode Lookup",
        "Started Enrollment – Passed Flow Step 1",
        "Started Enrollment – Passed Flow Step 2"
      ]
    },
    {
      "name":"lorem ipsum",
      "description":"Status Description",
      "segments":[
        "Moving in next 30 days",
        "Moving in next 90 days",
        "Not Moving"
      ]
    },
    {
      "name":"lorem ipsum",
      "description":"Interest description",
      "segments":[
        "Interested - Lots of Time Reading Many Pages",
        "Interested - Lots of Time Comparing Products/Prices"
      ]
    }
  ]
}

谢谢

【问题讨论】:

  • 那个 json 中的 null 是什么?
  • 请在您的问题中提供有效的 JSON。
  • 抱歉,已更正。上面的 json 只是一个应用程序输出的示例。其中的某些段可能为空。

标签: c# json asp.net-core .net-core json.net


【解决方案1】:

这是一个如何循环遍历 JSON 的示例:

JObject obj = JObject.Parse(json);

JArray segmentGroups = (JArray)obj.Properties().FirstOrDefault()?.Value; 
if (segmentGroups != null)
{
    foreach (JObject group in segmentGroups.Children<JObject>())
    {
        string name = (string)group["name"];
        string desc = (string)group["description"];
        string[] segments = group["segments"]?.ToObject<string[]>();
        
        Console.WriteLine("name: " + (name ?? "(null)"));
        Console.WriteLine("description: " + (desc ?? "(null)"));
        Console.WriteLine("segments: " + (segments != null ? "\n  " + string.Join("\n  ", segments) : "(null)"));
        Console.WriteLine();
    }
}

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

【讨论】:

    【解决方案2】:

    通过了解 JSON 结构,您可以使用名称格式为 JXxx 的各种类型来读取您想要的值。但是,这里有一种方便的方法可以使用json path 选择所需的令牌。这样,您可以方便地定位所需的令牌集并继续处理。我不太确定这种方法对性能的影响,但您可以权衡取舍(如果性能确实很重要,请先尝试对其进行基准测试)。

    代码可以这么简单:

    //suppose your example is the loaded JObject
    foreach (var group in example.SelectTokens("['lorem ipsum Segment Groups'][*]"))
    {
        var name = group["name"].Value<string>();
        var desc = group["description"].Value<string>();
        //check if they are null here ...
    
    }
    

    请注意我们通过将包含空格的键或路径包装在[''] 中来转义它们的方式。如果你的key不需要转义,可以直接在path中使用。

    【讨论】:

      猜你喜欢
      • 2021-03-14
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 2019-01-15
      • 2020-03-12
      • 1970-01-01
      相关资源
      最近更新 更多