您可以捐助,支持我们的公益事业。

1元 10元 50元





认证码:  验证码,看不清楚?请点击刷新验证码 必填



  求知 文章 文库 Lib 视频 iPerson 课程 认证 咨询 工具 讲座 Model Center   Code  
会员   
   
 
     
   
 订阅
  捐助
C#序列化和反序列化综合案例
 
作者: 技术弯弯
   次浏览      
 2020-12-25 
 
编辑推荐:

本文主要介绍了如何把DataTable转为JSON string、如何序列化?如何从txt文件中读取JSON格式的数据并反序列化?总结以及如何移植到web和其他序列化途径等相关。
本文来自于csdn,由火龙果Anna编辑推荐

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

该案例我是用WinForm做的,相信大部分人都是在Web开发中用,这个没关系。

首先你需要给你的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 :
* 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();
/// <summary>
/// 创建一个带有json格式的txt
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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.");
}
}
/// <summary>
/// Reading the specified file that contains a json string
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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<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.");
}
}
/// <summary>
/// Converts the specified JSON string to a object of type T.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonString"></param>
/// <returns></returns>
private T Deserialize<T>(string jsonString)
{
JavaScriptSerializer json = new JavaScriptSerializer();
return json.Deserialize<T>(jsonString);
}
private void btnDelFile_Click (object sender, EventArgs e)
{
if (File.Exists(filename))
{
File.Delete(filename);
MessageBox.Show("Deleted");
}
}
/// <summary>
/// Convert JSON string to Object
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnConvert_Click (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());
}
}
}
/// <summary>
/// Clear the listbox
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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;
}
/// <summary>
/// ConvertS an object to a JSON string
/// </summary>
/// <param name="o">Object</param>
/// <returns></returns>
private string ToJson(Object o)
{
JavaScriptSerializer j = new JavaScriptSerializer();
return j.Serialize(o);
}
/// <summary>
/// ConvertS an object to a JSON string When the string length is long
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
private string ToJson2(Object o)
{
JavaScriptSerializer j = new JavaScriptSerializer();
j.MaxJsonLength = Int32.MaxValue;
return j.Serialize(o);
}
/// <summary>
/// Converts datatable to JSON string.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
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字符串
}

/// <summary>
/// Json 字符串 转换为 DataTable数据集合
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
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;
}
}
}

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

下面我将会分开部分讲一下该案例的核心方法

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

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

/// <summary>
/// Json 字符串 转换为 DataTable数据集合
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
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;
}

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的方法

/// <summary>
/// Converts datatable to JSON string.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
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.创建一个方法

/// <summary>
/// ConvertS an object to a JSON string When the string length is long
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
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<Person> people = jss.Deserialize<List<Person>>(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);
}

下面是用到的方法

/// <summary>
/// Reading the specified file that contains a json string
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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<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.");
}
}

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是一个,那么可以通过键值对的方式来读取:

/// <summary>
/// 获取参数
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private System.Collections.Generic.Dictionary<String, Object> 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<String, Object> dicParameter = jss.Deserialize< System.Collections.Generic.Dictionary <String, Object>>(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;

   
次浏览       
 
相关文章

深度解析:清理烂代码
如何编写出拥抱变化的代码
重构-使代码更简洁优美
团队项目开发"编码规范"系列文章
 
相关文档

重构-改善既有代码的设计
软件重构v2
代码整洁之道
高质量编程规范
 
相关课程

基于HTML5客户端、Web端的应用开发
HTML 5+CSS 开发
嵌入式C高质量编程
C++高级编程
最新活动计划
LLM大模型应用与项目构建 12-26[特惠]
QT应用开发 11-21[线上]
C++高级编程 11-27[北京]
业务建模&领域驱动设计 11-15[北京]
用户研究与用户建模 11-21[北京]
SysML和EA进行系统设计建模 11-28[北京]
 
最新文章
.NET Core 3.0 正式公布:新特性详细解读
.NET Core部署中你不了解的框架依赖与独立部署
C# event线程安全
简析 .NET Core 构成体系
C#技术漫谈之垃圾回收机制(GC)
最新课程
.Net应用开发
C#高级开发技术
.NET 架构设计与调试优化
ASP.NET Core Web 开发
ASP.Net MVC框架原理与应用开发
更多...   
成功案例
航天科工集团子公司 DotNet企业级应用设计与开发
日照港集 .NET Framewor
神华信 .NET单元测试
台达电子 .NET程序设计与开发
神华信息 .NET单元测试
更多...