C#实现Json嵌套数组文件解析为对象

解析文件和结果如下:

 

一、思路分析

①观察发现是2层嵌套

②使用List集合实现--->创建类--->List集合--->Newtonsoft.json.dll

二、实现步骤

2.1、创建第2层嵌套的基础类:MapInfo.cs

namespace JsonDemo
{
    class MapInfo
    {
        public string mapName { get; set; }
        public string count { get; set; }
        public string type { get; set; }
        public string url { get; set; }
        public string progress { get; set; }
        public string waitCount { get; set; }

    }//Class_end
}

2.2、创建第1层嵌套的类:TestInfo.cs

using System.Collections.Generic;

namespace JsonDemo
{
    class TestInfo
    {
        public string XMText { get; set; }
        public string XMTYPE { get; set; }
        public string XMCount { get; set; }
        List<MapInfo> mapInfo = new List<MapInfo>();
        public List<MapInfo> mapInfos
        {
            get { return mapInfo; }
            set { mapInfo = value; }
        }

    }//Class_end
}

2.3、实现Json嵌套数组文件解析为对象

using JsonDemo;
using Kernal;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace XmlHelper
{
    class Program
    {
        static void Main(string[] args)
        {
            //解析Json文件
            string jsonData = GetJsonFile(@"e:\Zhonghejiaotong.json");
            Console.WriteLine(jsonData);
            List<TestInfo> testInfos = new List<TestInfo>();
            testInfos= JsonConvert.DeserializeObject<List<TestInfo>>(jsonData);

            for (int i = 0; i < testInfos.Count; i++)
            {
                Console.WriteLine("XMText:" + testInfos[i].XMText);
                Console.WriteLine("XMTYPE:" + testInfos[i].XMTYPE);
                Console.WriteLine("XMCount:" + testInfos[i].XMCount);
                List<MapInfo> mapInfos = testInfos[i].mapInfos;
                foreach (var item1 in mapInfos)
                {
                    Console.WriteLine("mapName:" + item1.mapName);
                    Console.WriteLine("count:" + item1.count);
                    Console.WriteLine("type:" + item1.type);
                    Console.WriteLine("url:" + item1.url);
                    Console.WriteLine("progress:" + item1.progress);
                    Console.WriteLine("waitCount:" + item1.waitCount);
                }
            }


            Console.ReadLine();

        }//Class_end

        //获取到本地的Json文件并且解析返回对应的json字符串
        public static string GetJsonFile(string filepath)
        {
            string json = string.Empty;

            using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
                {
                    json = sr.ReadToEnd().ToString();
                }
            }

            return json;
        }

    }
}

猜你喜欢

转载自blog.csdn.net/xiaochenXIHUA/article/details/90640530
今日推荐