我正在尝试动态查找其结构事先未知的 JSON 对象的叶节点的名称。首先,我将字符串解析为 JToken 列表,如下所示:
string req = @"{'creationRequestId':'A',
'value':{
'amount':1.0,
'currencyCode':'USD'
}
}";
var tokens = JToken.Parse(req);
Run Code Online (Sandbox Code Playgroud)
然后我想确定哪些是叶子。在上面的例子中,'creationRequestId':'A','amount':1.0和'currencyCode':'USD'都是树叶和名称creationRequestId,amount以及currencyCode。
下面的示例递归遍历 JSON 树并打印叶子名称:
public static void PrintLeafNames(IEnumerable<JToken> tokens)
{
foreach (var token in tokens)
{
bool isLeaf = token.Children().Count() == 1 && !token.Children().First().Children().Any();
if (token.Type == JTokenType.Property && isLeaf)
{
Console.WriteLine(((JProperty)token).Name);
}
if (token.Children().Any())
PrintLeafNames(token.Children<JToken>());
}
}
Run Code Online (Sandbox Code Playgroud)
这有效,打印:
creationRequestId
amount
currencyCode
Run Code Online (Sandbox Code Playgroud)
但是,我想知道是否有一个不那么难看的表达式来确定 JToken 是否是叶子:
bool isLeaf = token.Children().Count() == 1 && !token.Children().First().Children().Any();
Run Code Online (Sandbox Code Playgroud)
看起来您已经将叶子定义为任何JProperty其值没有任何子值的叶子。您可以使用 上的HasValues属性JToken来帮助做出此决定:
public static void PrintLeafNames(IEnumerable<JToken> tokens)
{
foreach (var token in tokens)
{
if (token.Type == JTokenType.Property)
{
JProperty prop = (JProperty)token;
if (!prop.Value.HasValues)
Console.WriteLine(prop.Name);
}
if (token.HasValues)
PrintLeafNames(token.Children());
}
}
Run Code Online (Sandbox Code Playgroud)
小提琴:https : //dotnetfiddle.net/e216YS
| 归档时间: |
|
| 查看次数: |
1139 次 |
| 最近记录: |