簡體   English   中英

從嵌套的Json Object獲取值

[英]Get Values from nested Json Object

我有一個嵌套的json格式,如下所示,我需要讀取所有節點,直到最后一個節點獲取節點名稱,節點值,屬性名稱,父節點。 我嘗試使用遞歸函數來讀取數據,但它無法正常工作。 請幫助一個簡單的解決方案來讀取數據。 (正是一個可以處理任意數量的節點和屬性的動態)

必需的輸出格式

   name     |   Value        | IsNode | Parent
------------------------------------------------
 updated    2014-01-01  false   record
 position   ambassador  true    record/person
 first_name Eliyahu     true    record/person/names
 alias      Eli         true    record/person/names/aliases
 country    ISRAEL      true    record/details/countries
 category   DIPLOMAT    false   record

Json輸入格式

{
  "Node": "record",
  "NodeValue": null,
  "ParentNode": "records",
  "Nodes": [
    {
      "Node": "person",
      "NodeValue": null,
      "ParentNode": "record",
      "Nodes": [
        {
          "Node": "title",
          "NodeValue": "Dr",
          "ParentNode": "person",
          "Nodes": [

          ],
          "Attributes": [

          ]
        },
        {
          "Node": "position",
          "NodeValue": "Ambassador",
          "ParentNode": "person",
          "Nodes": [

          ],
          "Attributes": [

          ]
        },
        {
          "Node": "names",
          "NodeValue": null,
          "ParentNode": "person",
          "Nodes": [
            {
              "Node": "first_name",
              "NodeValue": "Eliyahu",
              "ParentNode": "names",
              "Nodes": [

              ],
              "Attributes": [

              ]
            },
            {
              "Node": "last_name",
              "NodeValue": "BEN TURA",
              "ParentNode": "names",
              "Nodes": [

              ],
              "Attributes": [

              ]
            },
            {
              "Node": "aliases",
              "NodeValue": null,
              "ParentNode": "names",
              "Nodes": [
                {
                  "Node": "alias",
                  "NodeValue": "BEN TURA,Eli",
                  "ParentNode": "aliases",
                  "Nodes": [

                  ],
                  "Attributes": [

                  ]
                }
              ],
              "Attributes": [

              ]
            },
            {
              "Node": "alternative_spelling",
              "NodeValue": null,
              "ParentNode": "names",
              "Nodes": [

              ],
              "Attributes": [
                {
                  "Key": "{http://www.w3.org/2001/XMLSchema-instance}nil",
                  "Value": "true"
                }
              ]
            }
          ],
          "Attributes": [

          ]
        },
        {
          "Node": "agedata",
          "NodeValue": null,
          "ParentNode": "person",
          "Nodes": [
            {
              "Node": "age",
              "NodeValue": null,
              "ParentNode": "agedata",
              "Nodes": [

              ],
              "Attributes": [
                {
                  "Key": "{http://www.w3.org/2001/XMLSchema-instance}nil",
                  "Value": "true"
                }
              ]
            },
            {
              "Node": "as_of_date",
              "NodeValue": null,
              "ParentNode": "agedata",
              "Nodes": [

              ],
              "Attributes": [
                {
                  "Key": "{http://www.w3.org/2001/XMLSchema-instance}nil",
                  "Value": "true"
                }
              ]
            },
            {
              "Node": "dob",
              "NodeValue": null,
              "ParentNode": "agedata",
              "Nodes": [

              ],
              "Attributes": [
                {
                  "Key": "{http://www.w3.org/2001/XMLSchema-instance}nil",
                  "Value": "true"
                }
              ]
            },
            {
              "Node": "deceased",
              "NodeValue": null,
              "ParentNode": "agedata",
              "Nodes": [

              ],
              "Attributes": [
                {
                  "Key": "{http://www.w3.org/2001/XMLSchema-instance}nil",
                  "Value": "true"
                }
              ]
            }
          ],
          "Attributes": [

          ]
        }
      ],
      "Attributes": [
        {
          "Key": "ssn",
          "Value": ""
        },
        {
          "Key": "e-i",
          "Value": "M"
        }
      ]
    },
    {
      "Node": "details",
      "NodeValue": null,
      "ParentNode": "record",
      "Nodes": [
        {
          "Node": "passports",
          "NodeValue": null,
          "ParentNode": "details",
          "Nodes": [
            {
              "Node": "passport",
              "NodeValue": null,
              "ParentNode": "passports",
              "Nodes": [

              ],
              "Attributes": [
                {
                  "Key": "country",
                  "Value": ""
                },
                {
                  "Key": "{http://www.w3.org/2001/XMLSchema-instance}nil",
                  "Value": "true"
                }
              ]
            }
          ],
          "Attributes": [

          ]
        },
        {
          "Node": "place_of_birth",
          "NodeValue": null,
          "ParentNode": "details",
          "Nodes": [

          ],
          "Attributes": [
            {
              "Key": "{http://www.w3.org/2001/XMLSchema-instance}nil",
              "Value": "true"
            }
          ]
        },
        {
          "Node": "locations",
          "NodeValue": null,
          "ParentNode": "details",
          "Nodes": [
            {
              "Node": "location",
              "NodeValue": null,
              "ParentNode": "locations",
              "Nodes": [

              ],
              "Attributes": [
                {
                  "Key": "country",
                  "Value": "SENEGAL"
                },
                {
                  "Key": "city",
                  "Value": "Dakar"
                },
                {
                  "Key": "state",
                  "Value": "Dakar"
                },
                {
                  "Key": "{http://www.w3.org/2001/XMLSchema-instance}nil",
                  "Value": "true"
                }
              ]
            }
          ],
          "Attributes": [

          ]
        },
        {
          "Node": "countries",
          "NodeValue": null,
          "ParentNode": "details",
          "Nodes": [
            {
              "Node": "country",
              "NodeValue": "ISRAEL",
              "ParentNode": "countries",
              "Nodes": [

              ],
              "Attributes": [

              ]
            }
          ],
          "Attributes": [

          ]
        },
        {
          "Node": "companies",
          "NodeValue": null,
          "ParentNode": "details",
          "Nodes": [
            {
              "Node": "company",
              "NodeValue": null,
              "ParentNode": "companies",
              "Nodes": [

              ],
              "Attributes": [
                {
                  "Key": "{http://www.w3.org/2001/XMLSchema-instance}nil",
                  "Value": "true"
                }
              ]
            }
          ],
          "Attributes": [

          ]
        },
        {
          "Node": "keywords",
          "NodeValue": null,
          "ParentNode": "details",
          "Nodes": [
            {
              "Node": "keyword",
              "NodeValue": null,
              "ParentNode": "keywords",
              "Nodes": [

              ],
              "Attributes": [
                {
                  "Key": "{http://www.w3.org/2001/XMLSchema-instance}nil",
                  "Value": "true"
                }
              ]
            }
          ],
          "Attributes": [

          ]
        }
      ],
      "Attributes": [

      ]
    }
  ],
  "Attributes": [
    {
      "Key": "category",
      "Value": "DIPLOMAT"
    },
    {
      "Key": "editor",
      "Value": ""
    },
    {
      "Key": "entered",
      "Value": "2010-11-19"
    },
    {
      "Key": "sub-category",
      "Value": "PEP"
    },
    {
      "Key": "uid",
      "Value": "1389120"
    },
    {
      "Key": "updated",
      "Value": "2014-01-01"
    }
  ]
}

您可以使用Json.NET將JSON反序列化為以下類:

public class JsonNodes
{
    public string Node { get; set; }
    public string NodeValue { get; set; }
    public string ParentNode { get; set; }
    public List<JsonNodes> Nodes { get; set; }
    public List<JsonNodesAttribute> Attributes { get; set; }
}

public class JsonNodesAttribute
{
    public string Key { get; set; }
    public string Value { get; set; }
}

並且您可以使用此方法使用控制台應用程序以所需的輸出格式打印所有值:

private static void PrintValues(JsonNodes nodes, string parent)
{
    Console.WriteLine(string.Format("Name: {0}", nodes.Node));
    Console.WriteLine(string.Format("Value: {0}", nodes.NodeValue));
    Console.WriteLine("IsNode: true");
    Console.WriteLine(string.Format("Parent: {0}", parent)); 
    Console.WriteLine();

    if (parent == string.Empty)
    {
        parent += nodes.Node;
    }
    else
    {
        parent += string.Format("/{0}", nodes.Node);
    }

    foreach (JsonNodesAttribute attribute in nodes.Attributes)
    {
        Console.WriteLine(string.Format("Name: {0}", attribute.Key));
        Console.WriteLine(string.Format("Value: {0}", attribute.Value));
        Console.WriteLine("IsNode: false");
        Console.WriteLine(string.Format("Parent: {0}", parent));
    }

    Console.WriteLine();

    foreach (JsonNodes childNode in nodes.Nodes)
    {
        PrintValues(childNode, parent);
    }
}

假設您將JSON放到名為jsonInput的字符串變量中,以下是反序列化和打印其所有值的方法:

string jsonInput = ...; // put the above json here
JsonNodes nodes = JsonConvert.DeserializeObject<JsonNodes>(jsonInput);
PrintValues(nodes, string.Empty);

Console.ReadLine();

使用以下方法使用Json.NET枚舉您的JSON字符串:

void JsonVisitor(JToken node, int indent = 0)
{
    var indentString = new String(' ', indent * 4);
    Console.WriteLine("{0}+{1}: {2}", indentString, node["Node"], node["NodeValue"]);
    foreach (var attribute in node["Attributes"])
    {
        Console.WriteLine("{0} {1}: {2}", indentString, attribute["Key"], attribute["Value"]);
    }
    foreach (var subNode in node["Nodes"])
    {
        JsonVisitor(subNode, indent + 1);
    }
}

你可以像這樣調用它(如果jsonString是你的輸入):

var jsonObject = JObject.Parse(jsonString);
JsonVisitor(jsonObject.Root);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM