json数组的序列化和反序列化类

作者:袖梨 2022-06-25
 代码如下 复制代码

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;

 

///


/// json反序列化对象
///

public class Nature
{
    public string name { get; set; }//属性编号
    public string sex { get; set; }  //分类编号
}


///


/// json反序列化对象
///

public class Person
{
    public string name { get; set; }//属性编号
    public string sex { get; set; }  //分类编号
    public string age { get; set; }  //分类编号
    public string tel { get; set; }  //分类编号
}

 

public partial class _Default : System.Web.UI.Page
{


    protected void Page_Load(object sender, EventArgs e)
    {
        //复杂的json解析
        String json = "[{"name":"zhangsan","sex":"男"},{"name":"李四","sex":"男"},{"name":"张娟","sex":"女"},{"name":"慧娟","sex":"女"}]";
        List nt = Deserialize>(json);
        if (nt != null && nt.Count > 0)
        {
            Response.Write("复杂的json反序列化:
");
            foreach (Nature dt in nt)//打印集合中的元素               
            {
                Response.Write(dt.name+"
");
            }
        }


        //简单的json解析
        String json1 = "{"name":"张三","sex":"男","age":"25","tel":"1301554XXXX"}";


        JavaScriptSerializer js = new JavaScriptSerializer();
        Person pe = js.Deserialize(json1);

        Response.Write("
简单的json反序列化:" + pe.name);


        Response.Write("

序列化操作
");
        Response.Write("
复杂对象序列化
");
        List list = new List()  
        {  
            new Nature(){ name="张三", sex="男"},  
            new Nature(){ name="慧娟", sex="女"}  
        };
        string jsonTxt = JsonSerializer>(list);
        Response.Write(jsonTxt);

        Response.Write("

简单对象序列化
");
        Person pes = new Person();

        pes.name = "姐姐";
        pes.sex = "女";
        pes.tel = "1301554XXXX";
        pes.age = "23";

        string json1Txt = JsonSerializer(pes);
        Response.Write(json1Txt);
    }

 

    ///


    /// 反序列化json数组
    ///

    /// 对象
    /// json数组
    ///
    public  T Deserialize(string json)
    {
        T obj = Activator.CreateInstance();
        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            return (T)serializer.ReadObject(ms);
        }
    }


    ///


    /// 序列化对象为json
    ///

    /// 类型
    /// 对象
    ///
    public  string JsonSerializer(T t)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        MemoryStream ms = new MemoryStream();
        ser.WriteObject(ms, t);
        string jsonString = Encoding.UTF8.GetString(ms.ToArray());
        ms.Close();
        return jsonString;
    }
}

运行图片:

相关文章

精彩推荐