C# 序列化json数组 及 类 示例

VS→项目→管理NuGet程序包→浏览,输入json搜索,找到Newtonsoft.json安装就可以了

json解析反序列化–http://blog.csdn.net/wf824284257/article/details/59142029

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;


namespace JsonEnCodeTest
{
    class Program
    {
        class Person //辅助类
        {
            public string name
            {
                get;
                set;
            }
            public string sex
            {
                get;
                set;
            }
            public string country
            {
                get;
                set;
            }
            public Person(string name,string sex,string country)
            {
                this.name = name;
                this.sex = sex;
                this.country = country;
            }

            public void Say()
            {
                Console.WriteLine("im " + name + ", sex " + sex + " from " + country);
            }
        }

        class PersonGroup//辅助类
        {
            public string groupid
            {
                get;
                set;
            }
            public List persongroup;

            public PersonGroup()
            {
                persongroup = new List();
            }

            public void Say()
            {
                Console.WriteLine("group id = " + groupid);
                Console.WriteLine("members' selfintroduce :");
                foreach (Person p in persongroup)
                {
                    p.Say();
                }
            }
        }
        static void Main(string[] args)
        {
            List lp = new List();
            Person p = new Person("wufan","nan","China");
            lp.Add(p);
            p = new Person("Jusus", "nan", "America");
            lp.Add(p);
            p = new Person("sukura", "nv", "Japan");
            lp.Add(p);

            string jsonstr1 = JsonConvert.SerializeObject(lp);
            Console.WriteLine(jsonstr1);
            Console.WriteLine();

            PersonGroup pg = new PersonGroup();
            pg.groupid = "B140402";
            pg.persongroup = lp;
            //make json
            string jsonstr2 = JsonConvert.SerializeObject(pg);

            Console.WriteLine(jsonstr2);

            Console.Read();

        }
    }
}

你可能感兴趣的:(C#)