简体   繁体   English

如何使用 JSON.net 枚举嵌套的 JObject?

[英]How do I enumerate nested JObject using JSON.net?

I have a stringified json object which I parse using JObject.Parse and get the result below-我有一个字符串化的 json object 我使用JObject.Parse解析并得到以下结果 -

{{
   "payload": {
       "firstName": "John",
       "lastName": "Doe"
    }
}}

This was my input -这是我的输入 -

"{ \r\n\"payload\": {\r\n\t\"firstName\":\"John\", \r\n\t\"lastName\": \"Doe\"\r\n }}"

The extra brackets are the start and the end are added by the parser.额外的括号是解析器添加的开始和结束。 I want to iterate over this object and display the key value for first name and last name.我想迭代这个 object 并显示名字和姓氏的键值。

foreach (var property in jobject)
{
    Console.WriteLine("  {0}: {1}", property.Name, property.Value);
}

However, I don't know because of the two brackets or because of the nested structure I cannot get to the properties inside.但是,我不知道是因为两个括号还是因为嵌套结构我无法访问其中的属性。 I tried a recursive approach to parse the json but haven't been successful yet.我尝试了一种递归方法来解析 json 但还没有成功。 Can someone please help me with this?有人可以帮我吗?

If you want to iterate all nested objects as well you can do something like this:如果你也想迭代所有嵌套对象,你可以这样做:

var p = JObject.Parse(...);
foreach (var a in p.DescendantsAndSelf())
{
    if (a is JObject obj)
        foreach (var prop in obj.Properties())
            if (!(prop.Value is JObject) && !(prop.Value is JArray))
                Console.WriteLine("  {0}: {1}", prop.Name, prop.Value);
}

You can use LINQ to access to object. If it is not ok please add the part of parsing object to question.可以使用LINQ访问object,如果不行请将解析object的部分添加到问题中。

yourobj["payload"].ToObject<YourObject>()

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

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