简体   繁体   English

使用 C# 中的 JObject 解析 Json 键值的键/值

[英]Parse Json key/values of a key's value using JObject in C#

I am trying to get the sub key\values of a key's value.我正在尝试获取键值的子键\值。 What I am trying to accomplish is to remove the elements that are empty or have "-" or have "N/A".我要完成的是删除为空或具有“-”或具有“N/A”的元素。 I can not seem to figure out out to iterate over the values to search.我似乎无法弄清楚要遍历要搜索的值。

{
  "name": {
    "first": "Robert",
    "middle": "",
    "last": "Smith"
  },
  "age": 25,
  "DOB": "-",
  "hobbies": [
    "running",
    "coding",
    "-"
  ],
  "education": {
    "highschool": "N/A",
    "college": "Yale"
  }
}

Code:代码:

JObject jObject = JObject.Parse(response);

foreach (var obj in jObject)
{
    Console.WriteLine(obj.Key);
    Console.WriteLine(obj.Value);
}

I am trying to search "first":"Robert","middle":"","last":"Smith"我正在尝试搜索"first":"Robert","middle":"","last":"Smith"

You can use Descendants method to get child tokens of type JProperty , then filter their values and print them or remove one by one您可以使用Descendants方法获取JProperty类型的子令牌,然后过滤它们的值并打印它们或一一删除

var properties = json.Descendants()
    .OfType<JProperty>()
    .Where(p =>
    {
        if (p.Value.Type != JTokenType.String)
            return false;

        var value = p.Value.Value<string>();
        return string.IsNullOrEmpty(value);
    })
    .ToList();

    foreach (var property in properties) 
        property.Remove();

    Console.WriteLine(json);

Gives you the following result (with "middle": "" property removed)为您提供以下结果(删除了"middle": ""属性)

{
  "name": {
    "first": "Robert",
    "last": "Smith"
  },
  "age": 25,
  "DOB": "-",
  "hobbies": [
    "running",
    "coding",
    "-"
  ],
  "education": {
    "highschool": "N/A",
    "college": "Yale"
  }
}

You can also add more conditions to return statement, like return string.IsNullOrEmpty(value) || value.Equals("-");您还可以在return语句中添加更多条件,例如return string.IsNullOrEmpty(value) || value.Equals("-"); return string.IsNullOrEmpty(value) || value.Equals("-"); to remove "DOB": "-" property as well删除"DOB": "-"属性以及

You can recursively iterate JObject properties:您可以递归地迭代 JObject 属性:

    private static void IterateProps(JObject o)
    {
        foreach (var prop in o.Properties())
        {
            Console.WriteLine(prop.Name);
            if (prop.Value is JObject)
            {
                IterateProps((JObject)prop.Value);
            }
            else
            {
                Console.WriteLine(prop.Value);
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM