循环动态JSON以获取所有节点C# [英] Looping dynamic JSON to get all nodes C#

查看:1211
本文介绍了循环动态JSON以获取所有节点C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要循环播放多个JSON文件,并从中获取某些详细信息.但是,我希望有一个适合所有循环的大小,因为子节点在属性方面相互匹配.谁能建议我如何循环JSON节点?

I have multiple JSON files I need to loop and get certain details from these. However, I would like to have a one size fits all loop as the child nodes match one another in regards to properties. Can anyone suggest how I could loop my JSON nodes?

示例:

{
    "name": "Example",
    "description": "Example JSON",
    "properties":  {
         "foo": "bar",
         "foo1": "bar2",
         "foo3": "bar4",
    },
    "stages":  {
         "This is a stage": {
              "stageInfo1": "blah",
              "stageInfo2": "blah",
              "integration": {
                  "x": "x",
                  "y": "y",
                  "z": "z"
              }
         },
         "Another Stage": {
              "stageInfo1": "blah",
              "stageInfo2": "blah",
              "integration": {
                  "x": "x",
                  "y": "y",
                  "z": "z"
              }
         }
    }
 }

可以有数百个阶段.但是JSON的模式遵循这种通用模式,阶段可以具有随机名称,但是它们包含相同的定义.

There can be hundreds of stages. But the pattern of the JSON follows this general pattern, the stages can have random names, but they contain the same definition.

有什么简单的建议吗?

推荐答案

只需将数据建模到类中,并使用诸如Newtonsoft.JSON之类的反序列化库

Just model the data into classes and use a deserializer lib like Newtonsoft.JSON

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

public class Program
{
    public class Stage
    {
        [JsonProperty("stageInfo1")]
        public string StageInfo1;
    }

    public class JsonData
    {
        [JsonProperty("stages")]
        public Dictionary<string, Stage> Stages;
    }

    public static void Main()
    {
        var json = @"{
    ""name"": ""Example"",
    ""description"": ""Example JSON"",
    ""properties"":  {
         ""foo"": ""bar"",
         ""foo1"": ""bar2"",
         ""foo3"": ""bar4"",
    },
    ""stages"":  {
         ""This is a stage"": {
              ""stageInfo1"": ""blah"",
              ""stageInfo2"": ""blah"",
              ""integration"": {
                  ""x"": ""x"",
                  ""y"": ""y"",
                  ""z"": ""z""
              }
         },
         ""Another Stage"": {
              ""stageInfo1"": ""blah"",
              ""stageInfo2"": ""blah"",
              ""integration"": {
                  ""x"": ""x"",
                  ""y"": ""y"",
                  ""z"": ""z""
              }
         }
    }
 }";
        var data = JsonConvert.DeserializeObject<JsonData>(json);
        Console.WriteLine(data.Stages.Keys.ToArray());
    }
}

这篇关于循环动态JSON以获取所有节点C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆