首页 > 代码库 > json序列化和反序列化List

json序列化和反序列化List

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;

namespace JsonDome
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                List<Students> listObj = new List<Students>() { 
                    new Students {name="杨飞宰",age=25, sex="男"},
                    new Students {name="古天乐",age=44, sex="男"},
                    new Students {name="李汉平",age=25, sex="男"},
                    new Students {name="刘亦菲",age=27, sex="女"}
                };

                JsonData<List<Students>> obj = new JsonData<List<Students>>();
                obj.adminKid = 1;
                obj.buildingKid = 10;
                obj.appkey = "xxxxxxxxxxxxxxxxx";
                obj.ver = "1.0";
                obj.token = "xxxxxxxxxxxxxxxxx";
                obj.list = listObj;

                //先序列化Json格式数据
                string jsonText = JsonConvert.SerializeObject(obj);

                //反序列化对象
                JsonData<List<Students>> json = JsonConvert.DeserializeObject<JsonData<List<Students>>>(jsonText);
            }
        }
    }

    /// <summary>
    /// JSON数据类
    /// </summary>
    /// <typeparam name="T"><peparam>
    public class JsonData<T>
    {
        #region 系统参数
        public int adminKid { get; set; }
        public int buildingKid { get; set; }
        public string appkey { get; set; }
        public string ver { get; set; }
        public string token { get; set; }
        public T list { get; set; }
        #endregion
    }

    /// <summary>
    /// 学生实体
    /// </summary>
    [Serializable]
    public class Students
    {
        public string name { get; set; }
        public int age { get; set; }
        public string sex { get; set; }
    }
}


 

json序列化和反序列化List