【问题标题】:How to check if a nested path exists in json object for C#?如何检查 C# 的 json 对象中是否存在嵌套路径?
【发布时间】:2018-09-05 05:18:41
【问题描述】:

说想检查路径“L1.L2.L3”是否存在于 json 对象中。有一种方法可以逐步检查级别(How to check whether json object has some property),但我希望省去麻烦,而是检查路径。

【问题讨论】:

标签: c# json


【解决方案1】:

您可以使用 newtonsoft.json 中的 SelectToken 方法(token 为 null,当找不到匹配项时):

    string json = @"
{
    ""car"": {
        ""type"": {
            ""sedan"": {
                ""make"": ""honda"",
                ""model"": ""civics""
            }
        },                
    }
}";

    JObject obj = JObject.Parse(json);
    JToken token = obj.SelectToken("car.type.sedan.make",errorWhenNoMatch:false);
    Console.WriteLine(token.Path + " -> " + token?.ToString());

【讨论】:

  • 如果路径存在但属性值为null或空字符串,this也会返回null
  • 如果您需要 SelectToken 在 null 是可能的值时识别丢失的令牌(例如“myProp”:“”或“myProp”:null),那么您必须设置'errorWhenNoMatch:true)
【解决方案2】:

我最终使用了这样的扩展方法:

public static bool PathExists(this JObject obj, string path)
{
    var tokens = obj.SelectTokens(path);
    return tokens.Any();
}

但精神与公认的答案相同。

【讨论】:

    猜你喜欢
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 2020-02-28
    • 2021-12-23
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    相关资源
    最近更新 更多