C# 五十五、C#中使用Json

操作前安装LitJson:

将LitJson.dll文件添加到当前项目\bin\Debug文件夹中。

添加引用:在解决方案下找到引用,右击添加引用,浏览并添加上面的LitJson.dll文件。

导入命名空间:using LitJson;

解析

方法一:

using LitJson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            ReadJson(CreateJson());

            Console.ReadKey();
        }

        static string CreateJson()
        {
            Person person1 = new Person() { theName = "张三", theAge = 15 };
            Person person2 = new Person() { theName = "李四", theAge = 25 };
            Persons persons = new Persons { persons = new Person[] { person1, person2 } };

            string jsonStr = JsonMapper.ToJson(persons);
            return jsonStr;
        }

        static void ReadJson(string jsonStr)
        {
            Persons person = JsonMapper.ToObject<Persons>(jsonStr);
            foreach (Person item in person.persons)
            {
                Console.WriteLine(item.theName);
                Console.WriteLine(item.theAge);
            }
        }
    }

    public class Person
    {
        public string theName;
        public int theAge;
    }

    public class Persons
    {
        public Person[] persons;
    }
}

--->
张三
15
李四
25

方法二: 

[
{"ID":1,"Name":"宋江","Chuohao":"及时雨","Xing":"天魁星"},
{"ID":2,"Name":"林冲","Chuohao":"豹子头","Xing":"天雄星"},
{"ID":3,"Name":"柴进","Chuohao":"小旋风","Xing":"天贵星"},
{"ID":4,"Name":"吴用","Chuohao":"智多星","Xing":"天机星"},
{"ID":5,"Name":"时迁","Chuohao":"鼓上蚤","Xing":"地贼星"}
]
using LitJson;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            JsonData jd = JsonMapper.ToObject(File.ReadAllText(@"C:\Users\86515\Desktop\TestJson.txt"));

            List<Hero> hl = new List<Hero>();

            int ID = 0;
            string name = null;
            string chuohao = null;
            string xing = null;

            foreach (JsonData item in jd)
            {
                ID = int.Parse(item["ID"].ToString());
                name = item["Name"].ToString();
                chuohao = item["Chuohao"].ToString();
                xing = item["Xing"].ToString();
                Hero hero = new Hero() { _ID = ID, _name = name, _chuohao = chuohao, _xing = xing };
                hl.Add(hero);
            }

            foreach (var item in hl)
            {
                Console.WriteLine("ID:{0},姓名:{1},绰号:{2},应星:{3}",item._ID, item._name, item._chuohao, item._xing);
            }

            Console.ReadKey();
        }
    }
    class Hero
    {
        public int _ID;
        public string _name;
        public string _chuohao;
        public string _xing;
    }
}

--->
ID:1,姓名:宋江,绰号:及时雨,应星:天魁星
ID:2,姓名:林冲,绰号:豹子头,应星:天雄星
ID:3,姓名:柴进,绰号:小旋风,应星:天贵星
ID:4,姓名:吴用,绰号:智多星,应星:天机星
ID:5,姓名:时迁,绰号:鼓上蚤,应星:地贼星
{
"Name":"林冲", 
"Chuohao":"豹子头", 
"Xing":"天雄星",
"Story":
[
{"Storyid":1,"Storyname":"误入白虎堂"},
{"Storyid":2,"Storyname":"棒打洪教头"},
{"Storyid":3,"Storyname":"风雪山神庙"}
]
}
using LitJson;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            JsonData jd1 = JsonMapper.ToObject(File.ReadAllText(@"C:\Users\86515\Desktop\TestJson2.txt"));

            List<Hero.Story> h = new List<Hero.Story>();

            string name = jd1["Name"].ToString();
            string chuohao = jd1["Chuohao"].ToString();
            string xing = jd1["Xing"].ToString();

            JsonData jd2 = jd1["Story"];

            foreach (JsonData itemm in jd2)
            {
                string storyid = itemm["Storyid"].ToString();
                string storyname = itemm["Storyname"].ToString();
                Hero.Story story = new Hero.Story() { _storyid = storyid, _storyname = storyname };
                h.Add(story);
            }

            Hero hero = new Hero() { _name = name, _chuohao = chuohao, _xing = xing, _story = h };

            Console.WriteLine("姓名:{0},绰号:{1},应星:{2}", hero._name, hero._chuohao, hero._xing);
            foreach (Hero.Story itemm in hero._story)
            {
                Console.WriteLine("故事ID:{0},故事名字:{1}", itemm._storyid, itemm._storyname);
            }

            Console.ReadKey();
        }
    }

    class Hero
    {
        public string _name;
        public string _chuohao;
        public string _xing;
        public List<Story> _story;
        public class Story
        {
            public string _storyid;
            public string _storyname;
        }
    }
}

--->
姓名:林冲,绰号:豹子头,应星:天雄星
故事ID:1,故事名字:误入白虎堂
故事ID:2,故事名字:棒打洪教头
故事ID:3,故事名字:风雪山神庙
[

{

"Name":"林冲",
 
"Chuohao":"豹子头",
 
"Xing":"天雄星",
"Story":
[

{"Storyid":1,"Storyname":"误入白虎堂"},

{"Storyid":2,"Storyname":"棒打洪教头"},

{"Storyid":3,"Storyname":"风雪山神庙"}

]

},
{

"Name":"吴用",
 
"Chuohao":"智多星",
 
"Xing":"天机星",
"Story":
[

{"Storyid":1,"Storyname":"智取生辰纲"},

{"Storyid":2,"Storyname":"大破连环马"},

{"Storyid":3,"Storyname":"三打祝家庄"}

]

}

]
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using LitJson;

namespace Test_CSharp_Json
{
    class Program
    {
        static void Main(string[] args)
        {
            //读取文件
            JsonData jsonData = JsonMapper.ToObject(File.ReadAllText(@"C:\Users\86515\Desktop\TestJson.txt"));

            //声明变量,接收数据
            string name;
            string chuohao;
            string xing;
            int storyID;
            string storyName;

            JsonData story;
            List<Heros> listHeros = new List<Heros>();            

            //遍历获取数据
            foreach (JsonData item in jsonData)
            {
                name = item["Name"].ToString();
                chuohao = item["Chuohao"].ToString();
                xing = item["Xing"].ToString();
                story = item["Story"];

                List<Heros.Story> listStory = new List<Heros.Story>();

                foreach (JsonData ite in story)
                {
                    storyID =int.Parse(ite["Storyid"].ToString());
                    storyName = ite["Storyname"].ToString();
                    Heros.Story hstory = new Heros.Story() { _storyID = storyID, _storyName = storyName };
                    listStory.Add(hstory);
                }

                Heros heros = new Heros() { _name = name, _chuohao = chuohao, _xing = xing, _listStory = listStory };
                listHeros.Add(heros);
            }

            foreach (var item in listHeros)
            {
                Console.WriteLine("姓名:{0},绰号:{1},应星:{2}", item._name, item._chuohao, item._xing);

                foreach (var ite in item._listStory)
                {
                    Console.WriteLine("故事ID:{0},故事名字:{1}", ite._storyID, ite._storyName);
                }
            }
        }
    }
    class Heros
    {
        public string _name { get; set; }
        public string _chuohao { get; set; }
        public string _xing { get; set; }

        public List<Story> _listStory;
        public class Story
        {
            public int _storyID { get; set; }
            public string _storyName { get; set; }
        }
    }
}

--->
姓名:林冲,绰号:豹子头,应星:天雄星
故事ID:1,故事名字:误入白虎堂
故事ID:2,故事名字:棒打洪教头
故事ID:3,故事名字:风雪山神庙
姓名:吴用,绰号:智多星,应星:天机星
故事ID:1,故事名字:智取生辰纲
故事ID:2,故事名字:大破连环马
故事ID:3,故事名字:三打祝家庄

创建

方法一:

using LitJson;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {         
            //写
            StringBuilder sb = new StringBuilder();
            JsonWriter writer = new JsonWriter(sb);

            writer.WriteObjectStart();

            writer.WritePropertyName("Name");
            writer.Write("林冲");

            writer.WritePropertyName("Chuohao");
            writer.Write("豹子头");

            writer.WritePropertyName("Xing");
            writer.Write("天雄星");

            writer.WritePropertyName("Story");

            writer.WriteArrayStart();

            writer.WriteObjectStart();
            writer.WritePropertyName("Storyid");
            writer.Write(1);
            writer.WritePropertyName("Storyname");
            writer.Write("误入白虎堂");
            writer.WriteObjectEnd();

            writer.WriteObjectStart();
            writer.WritePropertyName("Storyid");
            writer.Write(2);
            writer.WritePropertyName("Storyname");
            writer.Write("棒打洪教头");
            writer.WriteObjectEnd();

            writer.WriteObjectStart();
            writer.WritePropertyName("Storyid");
            writer.Write(3);
            writer.WritePropertyName("Storyname");
            writer.Write("风雪山神庙");
            writer.WriteObjectEnd();

            writer.WriteArrayEnd();

            writer.WriteObjectEnd();

            //读
            JsonData jd1 = JsonMapper.ToObject(sb.ToString());

            List<Hero.Story> h2 = new List<Hero.Story>();

            string name = jd1["Name"].ToString();
            string chuohao = jd1["Chuohao"].ToString();
            string xing = jd1["Xing"].ToString();

            JsonData jd2 = jd1["Story"];

            foreach (JsonData itemm in jd2)
            {
                string storyid = itemm["Storyid"].ToString();
                string storyname = itemm["Storyname"].ToString();
                Hero.Story story = new Hero.Story() { _storyid = storyid, _storyname = storyname };
                h2.Add(story);
            }

            Hero hero = new Hero() { _name = name, _chuohao = chuohao, _xing = xing, _story = h2 };

            Console.WriteLine("姓名:{0},绰号:{1},应星:{2}", hero._name, hero._chuohao, hero._xing);
            foreach (Hero.Story itemm in hero._story)
            {
                Console.WriteLine("故事ID:{0},故事名字:{1}", itemm._storyid, itemm._storyname);
            }

            Console.ReadKey();
        }
    }

    class Hero
    {
        public string _name;
        public string _chuohao;
        public string _xing;
        public List<Story> _story;
        public class Story
        {
            public string _storyid;
            public string _storyname;
        }
    }
}

--->
姓名:林冲,绰号:豹子头,应星:天雄星
故事ID:1,故事名字:误入白虎堂
故事ID:2,故事名字:棒打洪教头
故事ID:3,故事名字:风雪山神庙

方法二: 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LitJson;

namespace TestJsonwithunity
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(CreateJson());

            Console.ReadKey();
        }
        public static string CreateJson()
        {
            Person person1 = new Person() { theName = "张三", theAge = 15 };
            Person person2 = new Person() { theName = "李四", theAge = 25 };
            Persons persons = new Persons { persons = new Person[] { person1, person2 } };

            string jsonStr = JsonMapper.ToJson(persons);
            return jsonStr;
        }
    }
    public class Person
    {
        public string theName;
        public int theAge;
    }

    public class Persons
    {
        public Person[] persons;
    }
}

--->
{"persons":[{"theName":"\u5F20\u4E09","theAge":15},{"theName":"\u674E\u56DB","theAge":25}]}

方法三: 

单个对象

using LitJson;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            JsonData jsonData = new JsonData();

            jsonData["name"] = "Gavin";

            jsonData["age"] = 28;

            jsonData["sex"] = "male";

            string json = jsonData.ToJson();

            Console.WriteLine(json);

            Console.ReadKey();
        }
    }
}

--->
{"name":"Gavin","age":28,"sex":"male"}

对象中包含对象 

using LitJson;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            JsonData jsonData = new JsonData();

            jsonData["name"] = "Gavin";

            jsonData["info"] = new JsonData();

            jsonData["info"]["age"] = 28;
            jsonData["info"]["sex"] = "male";

            string json = jsonData.ToJson();

            Console.WriteLine(json);

            Console.ReadKey();
        }
    }
}

--->
{"name":"Gavin","info":{"age":28,"sex":"male"}}

 对象与数组结合

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LitJson;

namespace TestJsonwithunity
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(CreateJson());

            Console.ReadKey();
        }
        static string CreateJson()
        {
            JsonData jsonData1 = new JsonData();
            jsonData1.SetJsonType(JsonType.Object);
            jsonData1["theName"] = "张三";
            jsonData1["theAge"] = 15;

            JsonData jsonData2 = new JsonData();
            jsonData2.SetJsonType(JsonType.Object);
            jsonData2["theName"] = "李四";
            jsonData2["theAge"] = 25;

            JsonData jsonDatas = new JsonData();
            jsonDatas.SetJsonType(JsonType.Array);
            jsonDatas.Add(jsonData1);
            jsonDatas.Add(jsonData2);

            JsonData jsonData = new JsonData();
            jsonData.SetJsonType(JsonType.Object);
            jsonData["Persons"] = jsonDatas;

            string jsonStr = jsonData.ToJson();
            return jsonStr;
        }
    }
}

--->
{"Persons":[{"theName":"\u5F20\u4E09","theAge":15},{"theName":"\u674E\u56DB","theAge":25}]}

文件

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LitJson;

namespace TestJsonwithunity
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"C:\Users\86515\Desktop\test.json";
            if (!File.Exists(path))
            {
                FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);    
                fs.Close();
                CreateJson(path);
            }
            else
            {
                CreateJson(path);
            }
        }
        static void CreateJson(string path)
        {
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);

            JsonData jsonData1 = new JsonData();
            jsonData1.SetJsonType(JsonType.Object);
            jsonData1["theName"] = "张三";
            jsonData1["theAge"] = 15;

            JsonData jsonData2 = new JsonData();
            jsonData2.SetJsonType(JsonType.Object);
            jsonData2["theName"] = "李四";
            jsonData2["theAge"] = 25;

            JsonData jsonDatas = new JsonData();
            jsonDatas.SetJsonType(JsonType.Array);
            jsonDatas.Add(jsonData1);
            jsonDatas.Add(jsonData2);

            JsonData jsonData = new JsonData();
            jsonData.SetJsonType(JsonType.Object);
            jsonData["Persons"] = jsonDatas;

            string jsonStr = jsonData.ToJson();

            byte[] b = Encoding.UTF8.GetBytes(jsonStr);
            fs.Write(b, 0, b.Length);
        }
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值