我能够读取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;
}但是我的儿子没有钥匙。如何进入每个段并检查name、description值是否不为空?
我的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"
]
}
]
}谢谢
发布于 2021-03-26 14:00:47
下面是一个如何遍历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();
}
}发布于 2021-03-26 14:19:01
通过了解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 ...
}请注意,我们通过将包含空格的键或路径包装在['']中来对其进行转义。如果您的键不需要转义,则可以直接在路径中使用它。
https://stackoverflow.com/questions/66810098
复制相似问题