c#迭代遍历带数组的json格式数据

【1】首先我们先创建一个带数组形式的json格式的数组

1)我们按照结构定义一个类,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.IO;

namespace ceshi1
{
    class Data
    {
        public string text
        {
            get;
            set;
        }
        public int nodeType
        {
            get;
            set;
        }
        public int nodeID
        {
            get;
            set;
        }
        public bool leaf
        {
            get;
            set;
        }
        public int devicedID
        {
            get;
            set;
        }
        public List<Data> children
        {
            get;
            set;
        }

    }
}

【2】我们来创造生成一个结构

//定义一个数据结构
            Data data = new Data();
            data.nodeType = 1;
            data.nodeID = 10;
            data.leaf = false;
            data.devicedID = 10;
            data.text = "直流监测";
            data.children = new List<Data>(){
                new Data(){
                    nodeType = 11,
                    nodeID = 101,
                    leaf = false,
                    devicedID = 101,
                    text = "广州局",
                    children = new List<Data>(){
                        new Data(){
                          nodeType = 111,
                          nodeID = 1011,
                          leaf = false,
                          devicedID = 1011,
                          text = "从化站",
                          children = new List<Data>(){
                            new Data(){
                                nodeType = 1111,
                                nodeID = 10111,
                                leaf = true,
                                devicedID = 10111,
                                text = "从化站#1主变",
                                children = new List<Data>(){}
                            },
                            new Data(){
                                nodeType = 1112,
                                nodeID = 10112,
                                leaf = true,
                                devicedID = 10112,
                                text = "从化站#2主变",
                                children = new List<Data>(){}
                            }
                          }
                        },
                        new Data(){
                          nodeType = 112,
                          nodeID = 1012,
                          leaf = false,
                          devicedID = 1012,
                          text = "板桥站",
                          children = new List<Data>(){
                              new Data(){
                                 nodeType = 1121,
                                 nodeID = 10121,
                                 leaf = true,
                                 devicedID = 1021,
                                 text = "板桥站#1主变",
                                 children = new List<Data>(){}
                              }
                          }
                        }
                    }
                },
                new Data(){
                    nodeType = 12,
                    nodeID = 102,
                    leaf = false,
                    devicedID = 102,
                    text = "深圳局",
                    children = new List<Data>(){
                        new Data(){
                            nodeType = 121,
                            nodeID = 1021,
                            leaf = false,
                            devicedID = 1021,
                            text = "福田站",
                            children = new List<Data>(){
                                new Data(){
                                    nodeType = 1211,
                                    nodeID = 10211,
                                    leaf = true,
                                    devicedID = 10211,
                                    text = "板桥站#1主变",
                                    children = new List<Data>(){}
                                }
                            }
                        }
                    }
                },
                new Data(){
                    nodeType = 13,
                    nodeID = 103,
                    leaf = false,
                    devicedID = 103,
                    text = "珠海局",
                    children = new List<Data>(){
                        new Data(){}
                    }
                }
            };

Console.WriteLine(data);

我们打印出来的对象为:ceshi1.Data;它是以一个对象的形式呈现;

【3】我们附加一点字符串/对象/json格式的转换方法讲解

首先引入第三方库:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

 

<a>将data序列化为json字符串
 string json = JsonConvert.SerializeObject(data);
 Console.WriteLine(json);

打印结果为(字符串):

{"text":"直流监测","nodeType":1,"nodeID":10,"leaf":false,"devicedID":10,"children":[{"text":"广州局","nodeType":11,"nodeID":101,"leaf":false,"devicedID":101,"children":[{"text":"从化站","nodeType":111,"nodeID":1011,"leaf":false,"devicedID":1011,"children":[{"text":"从化站#1主变","nodeType":1111,"nodeID":10111,"leaf":true,"devicedID":10111,"children":[]},{"text":"从化站#2主变","nodeType":1112,"nodeID":10112,"leaf":true,"devicedID":10112,"children":[]}]},{"text":"板桥站","nodeType":112,"nodeID":1012,"leaf":false,"devicedID":1012,"children":[{"text":"板桥站#1主变","nodeType":1121,"nodeID":10121,"leaf":true,"devicedID":1021,"children":[]}]}]},{"text":"深圳局","nodeType":12,"nodeID":102,"leaf":false,"devicedID":102,"children":[{"text":"福田站","nodeType":121,"nodeID":1021,"leaf":false,"devicedID":1021,"children":[{"text":"板桥站#1主 变","nodeType":1211,"nodeID":10211,"leaf":true,"devicedID":10211,"children":[]}]}]},{"text":"珠海局","nodeType":13,"nodeID":103,"leaf":false,"devicedID":103,"children":[{"text":null,"nodeType":0,"nodeID":0,"leaf":false,"devicedID":0,"children":null}]}]}

 

<b>有序列化,肯定有反序列化,将json反序列化为data,反序列化为对象
Data jsonData = JsonConvert.DeserializeObject<Data>(json);
Console.WriteLine(data);

打印结果为(对象):

ceshi1.Data;

 

<c>将json字符串格式化

JObject jo = (JObject)JsonConvert.DeserializeObject(json);
Console.WriteLine(jo);

打印结果为(json格式):

{
  "text": "直流监测",
  "nodeType": 1,
  "nodeID": 10,
  "leaf": false,
  "devicedID": 10,
  "children": [
    {
      "text": "广州局",
      "nodeType": 11,
      "nodeID": 101,
      "leaf": false,
      "devicedID": 101,
      "children": [
        {
          "text": "从化站",
          "nodeType": 111,
          "nodeID": 1011,
          "leaf": false,
          "devicedID": 1011,
          "children": [
            {
              "text": "从化站#1主变",
              "nodeType": 1111,
              "nodeID": 10111,
              "leaf": true,
              "devicedID": 10111,
              "children": []
            },
            {
              "text": "从化站#2主变",
              "nodeType": 1112,
              "nodeID": 10112,
              "leaf": true,
              "devicedID": 10112,
              "children": []
            }
          ]
        },
        {
          "text": "板桥站",
          "nodeType": 112,
          "nodeID": 1012,
          "leaf": false,
          "devicedID": 1012,
          "children": [
            {
              "text": "板桥站#1主变",
              "nodeType": 1121,
              "nodeID": 10121,
              "leaf": true,
              "devicedID": 1021,
              "children": []
            }
          ]
        }
      ]
    },
    {
      "text": "深圳局",
      "nodeType": 12,
      "nodeID": 102,
      "leaf": false,
      "devicedID": 102,
      "children": [
        {
          "text": "福田站",
          "nodeType": 121,
          "nodeID": 1021,
          "leaf": false,
          "devicedID": 1021,
          "children": [
            {
              "text": "板桥站#1主变",
              "nodeType": 1211,
              "nodeID": 10211,
              "leaf": true,
              "devicedID": 10211,
              "children": []
            }
          ]
        }
      ]
    },
    {
      "text": "珠海局",
      "nodeType": 13,
      "nodeID": 103,
      "leaf": false,
      "devicedID": 103,
      "children": [
        {
          "text": null,
          "nodeType": 0,
          "nodeID": 0,
          "leaf": false,
          "devicedID": 0,
          "children": null
        }
      ]
    }
  ]
}

到这一步,数据已经生成了,各位看官想要的三种数据形式都已经有了,接下来就是我们的重头戏了;

 

【4】迭代遍历取节点

需求:取出最底层的leaf = true或者Children为null的情况的节点所有的nodeType/nodeID/devicedID/text值;并以数组或者list的方式返回

a)下面我们定义一个迭代方法:

public static void FindAll(Data inputData, ref List<Data> data)
        {
            if (inputData.leaf)
            {
                data.Add(inputData);
            }
            else
            {
                if (inputData.children == null) return;
                foreach (var item in inputData.children)
                {
                    if (item.leaf)
                    {
                        data.Add(item);
                    }
                    else
                    {
                        FindAll(item,ref data);
                    }
                }
            }
        } 

b)我们在main函数(或者需要的地方)中调用,加上如下代码:

   //序列化为json字符串
            string json = JsonConvert.SerializeObject(data);
            //Console.WriteLine(json);

            //反序列化为对象
            Data jsonData = JsonConvert.DeserializeObject<Data>(json);
            //Console.WriteLine(data);

            //json格式化
            JObject jo = (JObject)JsonConvert.DeserializeObject(json);
            //Console.WriteLine(jo);

            //问题:
            //取出最底层的leaf = true或者Children为空的情况的节点所有的nodeType/nodeID/devicedID/text值?
            //需要迭代遍历?
            var resultData = new List<Data>();
            FindAll(data, ref  resultData);
            Console.ReadKey();

 

 

【5】检验是否正确

到这一步,我们基本上已经完成了,我们来测试一下最终的结果,遍历一下这个返回结果resultData

    for (int i = 0; i < resultData.Count;i++ )
            {
                Console.WriteLine(JsonConvert.SerializeObject(resultData[i]));
            }

输出结果如下:

{"text":"从化站#1主变","nodeType":1111,"nodeID":10111,"leaf":true,"devicedID":10111,"children":[]}
{"text":"从化站#2主变","nodeType":1112,"nodeID":10112,"leaf":true,"devicedID":10112,"children":[]}
{"text":"板桥站#1主变","nodeType":1121,"nodeID":10121,"leaf":true,"devicedID":1021,"children":[]}
{"text":"板桥站#1主变","nodeType":1211,"nodeID":10211,"leaf":true,"devicedID":10211,"children":[]}

显然,取出了全部的叶子结点

 

【6】结果源码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.IO;
using System.Data;
using System.Diagnostics;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ceshi1
{

    class Program
    {
        //public ArrayList al = new ArrayList();
        //public void GetAllDirList(string strBaseDir)
        //{

        //    DirectoryInfo di = new DirectoryInfo(strBaseDir);
        //    DirectoryInfo[] dirA = di.GetDirectories();
        //    for (int i = 0; i < dirA.Length; i++)
        //    {
        //        al.Add(dirA[i].FullName);
        //        Console.WriteLine(dirA[i]);
        //        Console.WriteLine(dirA[i].FullName);
        //        GetAllDirList(dirA[i].FullName);
        //    }
        //}

        static void Main(string[] args)
        {
            //定义一个数据结构
            Data data = new Data();
            data.nodeType = 1;
            data.nodeID = 10;
            data.leaf = false;
            data.devicedID = 10;
            data.text = "直流监测";
            data.children = new List<Data>()
            {
                new Data()
                {
                    nodeType = 11,
                    nodeID = 101,
                    leaf = false,
                    devicedID = 101,
                    text = "广州局",
                    children = new List<Data>()
                    {
                        new Data()
                        {
                            nodeType = 111,
                            nodeID = 1011,
                            leaf = false,
                            devicedID = 1011,
                            text = "从化站",
                            children = new List<Data>()
                            {
                                new Data()
                                {
                                    nodeType = 1111,
                                    nodeID = 10111,
                                    leaf = true,
                                    devicedID = 10111,
                                    text = "从化站#1主变",
                                    children = new List<Data>() {}
                                },
                                new Data()
                                {
                                    nodeType = 1112,
                                    nodeID = 10112,
                                    leaf = true,
                                    devicedID = 10112,
                                    text = "从化站#2主变",
                                    children = new List<Data>() {}
                                }
                            }
                        },
                        new Data()
                        {
                            nodeType = 112,
                            nodeID = 1012,
                            leaf = false,
                            devicedID = 1012,
                            text = "板桥站",
                            children = new List<Data>()
                            {
                                new Data()
                                {
                                    nodeType = 1121,
                                    nodeID = 10121,
                                    leaf = true,
                                    devicedID = 1021,
                                    text = "板桥站#1主变",
                                    children = new List<Data>() {}
                                }
                            }
                        }
                    }
                },
                new Data()
                {
                    nodeType = 12,
                    nodeID = 102,
                    leaf = false,
                    devicedID = 102,
                    text = "深圳局",
                    children = new List<Data>()
                    {
                        new Data()
                        {
                            nodeType = 121,
                            nodeID = 1021,
                            leaf = false,
                            devicedID = 1021,
                            text = "福田站",
                            children = new List<Data>()
                            {
                                new Data()
                                {
                                    nodeType = 1211,
                                    nodeID = 10211,
                                    leaf = true,
                                    devicedID = 10211,
                                    text = "板桥站#1主变",
                                    children = new List<Data>() {}
                                }
                            }
                        }
                    }
                },
                new Data()
                {
                    nodeType = 13,
                    nodeID = 103,
                    leaf = false,
                    devicedID = 103,
                    text = "珠海局",
                    children = new List<Data>()
                    {
                        new Data() {}
                    }
                }
            };

            //序列化为json字符串
            string json = JsonConvert.SerializeObject(data);
            //Console.WriteLine(json);

            //反序列化为对象
            Data jsonData = JsonConvert.DeserializeObject<Data>(json);
            //Console.WriteLine(data);

            //json格式化
            JObject jo = (JObject)JsonConvert.DeserializeObject(json);
            //Console.WriteLine(jo);

            //问题:
            //取出最底层的leaf = true或者Children为空的情况的节点所有的nodeType/nodeID/devicedID/text值?
            //需要迭代遍历?
            var resultData = new List<Data>();
            FindAll(data, ref  resultData);
            //Console.WriteLine(resultData);

            for (int i = 0; i < resultData.Count;i++ )
            {
                Console.WriteLine(JsonConvert.SerializeObject(resultData[i]));
            }
            Console.ReadKey();
        }


        public static void FindAll(Data inputData, ref List<Data> data)
        {
            if (inputData.leaf)
            {
                data.Add(inputData);
            }
            else
            {
                if (inputData.children == null) return;
                foreach (var item in inputData.children)
                {
                    if (item.leaf)
                    {
                        data.Add(item);
                    }
                    else
                    {
                        FindAll(item,ref data);
                    }
                }
            }
        }   
}
}

【6】监测过程源码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.IO;
using System.Data;
using System.Diagnostics;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ceshi1
{

    class Program
    {
        //public ArrayList al = new ArrayList();
        //public void GetAllDirList(string strBaseDir)
        //{

        //    DirectoryInfo di = new DirectoryInfo(strBaseDir);
        //    DirectoryInfo[] dirA = di.GetDirectories();
        //    for (int i = 0; i < dirA.Length; i++)
        //    {
        //        al.Add(dirA[i].FullName);
        //        Console.WriteLine(dirA[i]);
        //        Console.WriteLine(dirA[i].FullName);
        //        GetAllDirList(dirA[i].FullName);
        //    }
        //}

        static void Main(string[] args)
        {
            //定义一个数据结构
            Data data = new Data();
            data.nodeType = 1;
            data.nodeID = 10;
            data.leaf = false;
            data.devicedID = 10;
            data.text = "直流监测";
            data.children = new List<Data>(){
                new Data(){
                    nodeType = 11,
                    nodeID = 101,
                    leaf = false,
                    devicedID = 101,
                    text = "广州局",
                    children = new List<Data>(){
                        new Data(){
                          nodeType = 111,
                          nodeID = 1011,
                          leaf = false,
                          devicedID = 1011,
                          text = "从化站",
                          children = new List<Data>(){
                            new Data(){
                                nodeType = 1111,
                                nodeID = 10111,
                                leaf = true,
                                devicedID = 10111,
                                text = "从化站#1主变",
                                children = new List<Data>(){}
                            },
                            new Data(){
                                nodeType = 1112,
                                nodeID = 10112,
                                leaf = true,
                                devicedID = 10112,
                                text = "从化站#2主变",
                                children = new List<Data>(){}
                            }
                          }
                        },
                        new Data(){
                          nodeType = 112,
                          nodeID = 1012,
                          leaf = false,
                          devicedID = 1012,
                          text = "板桥站",
                          children = new List<Data>(){
                              new Data(){
                                 nodeType = 1121,
                                 nodeID = 10121,
                                 leaf = true,
                                 devicedID = 1021,
                                 text = "板桥站#1主变",
                                 children = new List<Data>(){}
                              }
                          }
                        }
                    }
                },
                new Data(){
                    nodeType = 12,
                    nodeID = 102,
                    leaf = false,
                    devicedID = 102,
                    text = "深圳局",
                    children = new List<Data>(){
                        new Data(){
                            nodeType = 121,
                            nodeID = 1021,
                            leaf = false,
                            devicedID = 1021,
                            text = "福田站",
                            children = new List<Data>(){
                                new Data(){
                                    nodeType = 1211,
                                    nodeID = 10211,
                                    leaf = true,
                                    devicedID = 10211,
                                    text = "板桥站#1主变",
                                    children = new List<Data>(){}
                                }
                            }
                        }
                    }
                },
                new Data(){
                    nodeType = 13,
                    nodeID = 103,
                    leaf = false,
                    devicedID = 103,
                    text = "珠海局",
                    children = new List<Data>(){
                        new Data(){}
                    }
                }
            };

            //序列化为json字符串
            string json = JsonConvert.SerializeObject(data);
            // Console.WriteLine(json);

            //反序列化为对象
            Data jsonData = JsonConvert.DeserializeObject<Data>(json);
            //取出最底层的leaf = true或者Children为空的情况的节点所有的nodeType/nodeID/devicedID/text值?

            FindAll(jsonData);
            Console.ReadKey();
        }


        public static void FindAll(Data inputData)
        {
            if (inputData.leaf)
            {
                Console.WriteLine("leaf:{0}, nodeType:{1}, nodeID:{2}, devicedID:{3}, text: {4}, children is null:{5}"
                    , inputData.leaf
                    , inputData.nodeType
                    , inputData.nodeID
                    , inputData.devicedID
                    , inputData.text
                    , inputData.children == null);
            }
            else
            {
                if (inputData.children == null) return;
                foreach (var item in inputData.children)
                {
                    if (item.leaf)
                    {
                        Console.WriteLine(
                            "leaf:{0}, nodeType:{1}, nodeID:{2}, devicedID:{3}, text: {4}, children is null:{5}"
                            , item.leaf
                            , item.nodeType
                            , item.nodeID
                            , item.devicedID
                            , item.text
                            , item.children == null);
                        //我想把取出来结果以对象的方式放到数组或者一个List集合里面去,然后再返回这个集合或者数组(最好用数组),谢谢
                        //数组类似于:[{leaf:True, nodeType:1111, nodeID:10111, devicedID:10111, text: 从化站#1主变, children is null:False},{leaf:True, nodeType:1112, nodeID:10112, devicedID:10112, text: 从化站#2主变, children is null:False}]


                    }
                    else
                    {
                        FindAll(item);
                    }
                }
            }
        }
    }
}

本文源于zhuxiaoge(http://www.cnblogs.com/zhuxiaoge/p/7090544.html),如有转载请标明出处,不甚感激!!!

 

posted @ 2017-06-28 16:58  朱小哥  阅读(2967)  评论(0编辑  收藏  举报