C#序列化和反序列化综合案例

大家好,我是网呦,今天分享的内容是:C#序列号和反序列化的实用案例。

大纲

1.贴出主文件的所有代码
2.逐个分析之如何把JSON string 转为DataTable
3.如何把DataTable转为JSON string
4.如何序列化?
5.如何从txt文件中读取JSON格式的数据并反序列化
6.总结以及如何移植到web和其他序列化途径

1.贴出主文件的所有代码

该案例我是用WinForm做的,相信大部分人都是在Web开发中用,这个没关系。首先,给大家贴出源码喽,
https://yunpan.cn/cPMADjQr2M5v2 访问密码 f15d

首先你需要给你的Project引入所需的dll。System.Web和System.Web.Extensions如图
C#序列化和反序列化综合案例_第1张图片

好的,下面是我用程序创建的一个JSON 格式的名为”json.txt”的文本。

[{"name":"Jason","id":"20130001","phone":"13579246810"},{"name":"Alias","id":"20130002","phone":"18437965529"},{"name":"Tom","id":"20130003","phone":"15090246296"}]

下面是我的WinForm的UI和识别代码逻辑效果
C#序列化和反序列化综合案例_第2张图片
如何你解析的JSON不是多个对象,而是一个,如:

{"name":"Jason","id":"20130001","phone":"13579246810"}

那么执行效果如图:
C#序列化和反序列化综合案例_第3张图片

好的,作为辅助,我创建了一个class Person,代码如下:

 public class Person
    {
        private string _name;
        private int _id;
        private string _phone;

        public string Phone
        {
            get { return _phone; }
            set { _phone = value; }
        }

        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public Person() { }
        public Person(int id, string name, string phone)
        {
            this._id = id;
            this._name = name;
            this._phone = phone;
        }

    }

然后就是主逻辑代码:如下,

/*
 * Author     : 刘壮
 * Edit Date  : 2016/5/1
 * Email      :  
 * Description: 1.Create a txt file with json string.
 *              2.Deserialize JSON string by two ways.
 *              3.You can type a json with object or a json array.
 */
using System;
using System.Windows.Forms;
using System.IO;
using System.Web;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Data;
using System.Collections;

namespace _02_反序列化和反序列化
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private string filename = "json.txt";
        JavaScriptSerializer jss = new JavaScriptSerializer();

        /// 
        /// 创建一个带有json格式的txt
        /// 
        /// 
        /// 
        private void btnCreateJson_Click(object sender, EventArgs e)
        {
            //Create a new  document with json string.

            //Judge whether the specified file exists.
            if (!File.Exists(filename))
            {
                //MessageBox.Show("no existence");
                //File.Create(filename);
                //Write a json string into the specified file
                using (StreamWriter sw = new StreamWriter(filename, false, System.Text.Encoding.UTF8))
                {
                    //下面通过一个例子演示了如何从json转为DataTable,再由DataTable转为JSON string.
                    string json = string.Empty;
                    json = "[{\"name\":\"Jason\",\"id\":20130001,\"phone\":\"13579246810\"}," +
                                   "{\"name\":\"Alias\",\"id\":20130002,\"phone\":\"18437965529\"}," +
                                   "{\"name\":\"Tom\",\"id\":20130003,\"phone\":\"15090246296\"}]";

                    DataTable dt = new DataTable();
                    //json = ToJson(new Person(20130001,"Json","12345678901"));
                    dt = JsonToDataTable(json);
                    json = DataTableToJson(dt);
                    sw.Write(json);
                }
                MessageBox.Show("the specified have been created!");
            }
            else
            {
                MessageBox.Show("the file was existing.you can delete it then re click it.");
            }
        }

        /// 
        /// Reading the specified file that contains a json string
        /// 
        /// 
        /// 
        private void btnAnalyzeJson_Click(object sender, EventArgs e)
        {
            //Judge whether the specified file exists.
            if (File.Exists(filename))
            {
                //Getting the string that is a specified file
                using (StreamReader sr = new StreamReader(filename, System.Text.Encoding.UTF8))
                {
                    string json = sr.ReadToEnd();
                    //analyze the json string.
                    txtOrgJson.Text = json;


                    //The first method.(For one object)
                    //Person p = jss.Deserialize(json,typeof(Person)) as Person;
                    //txtAnalysedJson.Text = "name="+p.Name+"\r\nid="+p.Id+"\r\nphone="+p.Phone;

                    //The second method.(For a lots objects)
                    List people = jss.Deserialize>(json);
                    StringBuilder sb = new StringBuilder();
                    PropertyInfo[] piArr = typeof(Person).GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                    if (people.Count == 0)
                    {
                        DeserializeToObject(json);
                        return;
                    }

                    //Get the name and value of the specified class Person automatically.
                    foreach (var person in people)
                    {
                        sb.Clear();
                        foreach (PropertyInfo pi in piArr)
                        {
                            sb.Append(pi.Name + "=" + pi.GetValue(person));
                            sb.Append("\t ");
                        }
                        listAll.Items.Add(sb.ToString());
                        //listAll.Items.Add("name=" + person.Name + "\tid=" + person.Id + "\tphone=" + person.Phone);
                    }
                }
            }
            else
            {
                MessageBox.Show("Cannot find the specified file.Please click the up button of this.");
            }
        }

        /// 
        /// Converts the specified JSON string to a object of type T.
        /// 
        /// 
        /// 
        /// 
        private T Deserialize(string jsonString)
        {
            JavaScriptSerializer json = new JavaScriptSerializer();
            return json.Deserialize(jsonString);
        }

        private void btnDelFile_Click(object sender, EventArgs e)
        {
            if (File.Exists(filename))
            {
                File.Delete(filename);
                MessageBox.Show("Deleted");
            }
        }

        /// 
        /// Convert JSON string to Object
        /// 
        /// 
        /// 
        private void btnConvert_Click(object sender, EventArgs e)
        {
            string json = txtOrgJson.Text.Trim();
            if (!String.IsNullOrEmpty(json))
            {
                List lPerson = Deserialize>(json);

                StringBuilder sb = new StringBuilder();
                PropertyInfo[] piArr = typeof(Person).GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                if (lPerson.Count == 0)
                {
                    DeserializeToObject(json);
                    return;
                }

                //Get the name and value of the specified class Person automatically.
                foreach (var person in lPerson)
                {
                    sb.Clear();
                    foreach (PropertyInfo pi in piArr)
                    {
                        sb.Append(pi.Name + "=" + pi.GetValue(person));
                        sb.Append("\t ");
                    }
                    listAll.Items.Add(sb.ToString());
                }

            }
        }

        /// 
        /// Clear the listbox
        /// 
        /// 
        /// 
        private void btnClear_Click(object sender, EventArgs e)
        {
            listAll.Items.Clear();
        }

        private void DeserializeToObject(string data)
        {
            Person p = jss.Deserialize(data, typeof(Person)) as Person;
            txtAnalysedJson.Text = "name=" + p.Name + "\r\nid=" + p.Id + "\r\nphone=" + p.Phone;
        }

        /// 
        /// ConvertS an object to a JSON string 
        /// 
        /// Object
        /// 
        private string ToJson(Object o)
        {
            JavaScriptSerializer j = new JavaScriptSerializer();
            return j.Serialize(o);
        }

        /// 
        ///  ConvertS an object to a JSON string When the string length is long
        /// 
        /// 
        /// 
        private string ToJson2(Object o)
        {
            JavaScriptSerializer j = new JavaScriptSerializer();
            j.MaxJsonLength = Int32.MaxValue;
            return j.Serialize(o);
        }

        /// 
        /// Converts datatable to JSON string.
        /// 
        /// 
        /// 
        private string DataTableToJson(DataTable dt)
        {
            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
            ArrayList arrayList = new ArrayList();
            foreach (DataRow dataRow in dt.Rows)
            {
                Dictionary<string, object> dictionary = new Dictionary<string, object>(); //实例化一个参数集合
                foreach (DataColumn dataColumn in dt.Columns)
                {
                    dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToString());
                }
                arrayList.Add(dictionary); //ArrayList集合中添加键值
            }

            return javaScriptSerializer.Serialize(arrayList); //返回一个json字符串
        }



        /// 
        /// Json 字符串 转换为 DataTable数据集合
        /// 
        /// 
        /// 
        public  DataTable JsonToDataTable(string json)
        {
            DataTable dataTable = new DataTable(); //实例化
            DataTable result;
            try
            {
                JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
                javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
                ArrayList arrayList = javaScriptSerializer.Deserialize(json);
                if (arrayList.Count > 0)
                {
                    foreach (Dictionary<string, object> dictionary in arrayList)
                    {
                        if (dictionary.Keys.Count == 0)
                        {
                            result = dataTable;
                            return result;
                        }
                        if (dataTable.Columns.Count == 0)
                        {
                            foreach (string current in dictionary.Keys)
                            {
                                dataTable.Columns.Add(current, dictionary[current].GetType());
                            }
                        }
                        DataRow dataRow = dataTable.NewRow();
                        foreach (string current in dictionary.Keys)
                        {
                            dataRow[current] = dictionary[current];
                        }

                        dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
                    }
                }
            }
            catch
            {
            }
            result = dataTable;
            return result;
        }
    }
}

上面用到了很多方法,都是很重要很重要很重要的,重要是事情要说三遍!!!由于使用的WinForm开发的,所以上面的代码中会含有部分控件的Name。
下面我将会分开部分讲一下该案例的核心方法

2.逐个分析之如何把JSON string 转为DataTable

1.首先创建一个JsonToDataTable的通用方法

 /// 
        /// Json 字符串 转换为 DataTable数据集合
        /// 
        /// 
        /// 
        public  DataTable JsonToDataTable(string json)
        {
            DataTable dataTable = new DataTable(); //实例化
            DataTable result;
            try
            {
                JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
                javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
                ArrayList arrayList = javaScriptSerializer.Deserialize(json);
                if (arrayList.Count > 0)
                {
                    foreach (Dictionary<string, object> dictionary in arrayList)
                    {
                        if (dictionary.Keys.Count == 0)
                        {
                            result = dataTable;
                            return result;
                        }
                        if (dataTable.Columns.Count == 0)
                        {
                            foreach (string current in dictionary.Keys)
                            {
                                dataTable.Columns.Add(current, dictionary[current].GetType());
                            }
                        }
                        DataRow dataRow = dataTable.NewRow();
                        foreach (string current in dictionary.Keys)
                        {
                            dataRow[current] = dictionary[current];
                        }

                        dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
                    }
                }
            }
            catch
            {
            }
            result = dataTable;
            return result;
        }

2.新建一个json字符串并赋值。然后调用上面的方法就可以转为DataTable了。

string json = string.Empty;
                    json = "[{\"name\":\"Jason\",\"id\":20130001,\"phone\":\"13579246810\"}," +
                                   "{\"name\":\"Alias\",\"id\":20130002,\"phone\":\"18437965529\"}," +
                                   "{\"name\":\"Tom\",\"id\":20130003,\"phone\":\"15090246296\"}]";
   DataTable dt = JsonToDataTable(json);

3.如何把DataTable转为JSON string

1.新建一个DataTableToJson的方法

/// 
        /// Converts datatable to JSON string.
        /// 
        /// 
        /// 
        private string DataTableToJson(DataTable dt)
        {
            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
            javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
            ArrayList arrayList = new ArrayList();
            foreach (DataRow dataRow in dt.Rows)
            {
                Dictionary<string, object> dictionary = new Dictionary<string, object>(); //实例化一个参数集合
                foreach (DataColumn dataColumn in dt.Columns)
                {
                    dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToString());
                }
                arrayList.Add(dictionary); //ArrayList集合中添加键值
            }

            return javaScriptSerializer.Serialize(arrayList); //返回一个json字符串
        }

2.调用方法,传入一个DataTable就可以。哪个DataTable都可以的。

string json = DataTableToJson(dt);

4.如何序列化?

1.创建一个方法

        /// 
        ///  ConvertS an object to a JSON string When the string length is long
        /// 
        /// 
        /// 
        private string ToJson2(Object o)
        {
            JavaScriptSerializer j = new JavaScriptSerializer();
            j.MaxJsonLength = Int32.MaxValue;
            return j.Serialize(o);
        }

2.就这样传入一个对象就行了。
比如:Person p = new Person();string json = ToJson2(p);
上面在DataTable中也用到过序列化的Demo,可以参考用到大量数据时进行转JSON

5.如何从txt文件中读取JSON格式的数据并反序列化

简述下流程:
1.判断txt的存在
2.读取txt的内容
3.通过下面的代码把JSON对象存入一个泛型中

List people = jss.Deserialize<List>(json);

4.通过映射,自动获取到JSON对应类(Class)的属性名,实现自动化并通过遍历输出

PropertyInfo[] piArr = typeof(Person).GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                    if (people.Count == 0)
                    {
                        DeserializeToObject(json);
                        return;
                    }

                    //Get the name and value of the specified class Person automatically.
                    foreach (var person in people)
                    {
                        sb.Clear();
                        foreach (PropertyInfo pi in piArr)
                        {
                            sb.Append(pi.Name + "=" + pi.GetValue(person));
                            sb.Append("\t ");
                        }
                        listAll.Items.Add(sb.ToString());
                        //listAll.Items.Add("name=" + person.Name + "\tid=" + person.Id + "\tphone=" + person.Phone);
                    }

下面是用到的方法

        /// 
        /// Reading the specified file that contains a json string
        /// 
        /// 
        /// 
        private void btnAnalyzeJson_Click(object sender, EventArgs e)
        {
            //Judge whether the specified file exists.
            if (File.Exists(filename))
            {
                //Getting the string that is a specified file
                using (StreamReader sr = new StreamReader(filename, System.Text.Encoding.UTF8))
                {
                    string json = sr.ReadToEnd();
                    //analyze the json string.
                    txtOrgJson.Text = json;


                    //The first method.(For one object)
                    //Person p = jss.Deserialize(json,typeof(Person)) as Person;
                    //txtAnalysedJson.Text = "name="+p.Name+"\r\nid="+p.Id+"\r\nphone="+p.Phone;

                    //The second method.(For a lots objects)
                    List people = jss.Deserialize>(json);
                    StringBuilder sb = new StringBuilder();
                    PropertyInfo[] piArr = typeof(Person).GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                    if (people.Count == 0)
                    {
                        DeserializeToObject(json);
                        return;
                    }

                    //Get the name and value of the specified class Person automatically.
                    foreach (var person in people)
                    {
                        sb.Clear();
                        foreach (PropertyInfo pi in piArr)
                        {
                            sb.Append(pi.Name + "=" + pi.GetValue(person));
                            sb.Append("\t ");
                        }
                        listAll.Items.Add(sb.ToString());
                        //listAll.Items.Add("name=" + person.Name + "\tid=" + person.Id + "\tphone=" + person.Phone);
                    }
                }
            }
            else
            {
                MessageBox.Show("Cannot find the specified file.Please click the up button of this.");
            }
        }

6.总结以及如何移植到web和其他序列化途径

先写这么多,你有什么疑问也可以留言交流一下,该案例仅供参考,不代表标准案例。另外,由于这里用的是WinForm开发,你在Web里通过POST方法传入json数据时,可能需要通过下面的方法获取到json string
StreamReader reader = new StreamReader(context.Request.InputStream);
        //比如得到json字符串:strJson={"key3":"xdp-gacl","key4":"白皇"}
        String strJson = HttpUtility.UrlDecode(reader.ReadToEnd());

然后下面就是按上面的案例中的方法进行优化,调整。
另外呢,如果是传入的JSON string是一个,那么可以通过键值对的方式来读取:

    /// 
    /// 获取参数
    /// 
    /// "context">
    /// 
    private System.Collections.Generic.Dictionary GetParameter(HttpContext context)
    {
        StreamReader reader = new StreamReader(context.Request.InputStream);
        //得到json字符串:strJson={"key3":"xdp-gacl","key4":"白虎神皇"}
        String strJson = HttpUtility.UrlDecode(reader.ReadToEnd());
        System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
        //将json字符串反序列化成一个Dictionary对象
        System.Collections.Generic.Dictionary dicParameter = jss.Deserialize.Collections.Generic.Dictionary>(strJson);
        return dicParameter;
    }

调用方式

Dictionary<String, Object> dicParameter = GetParameter(context);
string key3 = dicParameter["keyword"].ToString();

另外呢,除了上面的序列化之外,还可以用下面的方法:

public static string ToJsJson(object item)
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());
        using (MemoryStream ms = new MemoryStream())
        {
            serializer.WriteObject(ms, item);
            StringBuilder sb = new StringBuilder("");
            sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
            return sb.ToString();
        }
    }

需要你引用:using System.Runtime.Serialization.Json;

好,暂时就分享到这里。谢谢!

你可能感兴趣的:(【编程语言】)