JSON

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

字号+ 作者:H5之家 来源:H5之家 2016-05-08 14:06 我要评论( )

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如图

这里写图片描述

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

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

下面是我的WinForm的UI和识别代码逻辑效果

这里写图片描述


如何你解析的JSON不是多个对象,而是一个,如:

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

那么执行效果如图:

这里写图片描述

好的,作为辅助,我创建了一个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 : xiaozbc@sina.com * 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_反序列化和反序列化 { Form1 : Form { public Form1() { InitializeComponent(); } private string filename = "json.txt"; JavaScriptSerializer jss = new JavaScriptSerializer(); 创建一个带有json格式的txt (object sender, EventArgs e) { (!File.Exists(filename)) { (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 (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; List<Person> people = jss.Deserialize<List<Person>>(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<T>(string jsonString) { JavaScriptSerializer json = new JavaScriptSerializer(); return json.Deserialize<T>(jsonString); } (object sender, EventArgs e) { if (File.Exists(filename)) { File.Delete(filename); MessageBox.Show("Deleted"); } } Convert JSON string to Object (object sender, EventArgs e) { string json = txtOrgJson.Text.Trim(); if (!String.IsNullOrEmpty(json)) { List<Person> lPerson = Deserialize<List<Person>>(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 (object sender, EventArgs e) { listAll.Items.Clear(); } (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 (Object o) { JavaScriptSerializer j = new JavaScriptSerializer(); return j.Serialize(o); } ConvertS an object to a JSON string When the string length is long (Object o) { JavaScriptSerializer j = new JavaScriptSerializer(); j.MaxJsonLength = Int32.MaxValue; return j.Serialize(o); } Converts datatable to JSON string. (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<ArrayList>(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; } } }

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • C++ Builder 里面使用 JsonCpp 和 JsonCpp 支持 UNICODE (UTF

    C++ Builder 里面使用 JsonCpp 和 JsonCpp 支持 UNICODE (UTF

    2016-04-08 15:00

  • 详解C++的JSON静态链接库JsonCpp的使用方法

    详解C++的JSON静态链接库JsonCpp的使用方法

    2016-04-02 14:00

  • C++的Json解析库:jsoncpp

    C++的Json解析库:jsoncpp

    2016-01-26 09:22

  • jsoncpp 库的c++实现,里面还有测试程序,是不可多得的学习资料 Li

    jsoncpp 库的c++实现,里面还有测试程序,是不可多得的学习资料 Li

    2016-01-14 19:29

网友点评
h