C#--序列化和反序列化--JSON和对象互转方法
1,方法1,通用方法,以下方法是转载别人的
1,添加引用
【1.1】引用:System.Runtime.Serialization.dll
【1.2】using System.Runtime.Serialization.Json;
2,序列化和反序列化的方法
/// <summary> /// 转换对象为JSON格式数据 /// </summary> /// <typeparam name="T">类</typeparam> /// <param name="obj">对象</param> /// <returns>字符格式的JSON数据</returns> public static string GetJSON<T>(object obj) { string result = String.Empty; try { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { serializer.WriteObject(ms, obj); result = System.Text.Encoding.UTF8.GetString(ms.ToArray()); } } catch (Exception ex) { throw ex; } return result; } private static string getJsonByObject(Object obj) { //实例化DataContractJsonSerializer对象,需要待序列化的对象类型 DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); //实例化一个内存流,用于存放序列化后的数据 MemoryStream stream = new MemoryStream(); //使用WriteObject序列化对象 serializer.WriteObject(stream, obj); //写入内存流中 byte[] dataBytes = new byte[stream.Length]; stream.Position = 0; stream.Read(dataBytes, 0, (int)stream.Length); //通过UTF8格式转换为字符串 return Encoding.UTF8.GetString(dataBytes); } private static Object getObjectByJson(string jsonString, Object obj) { //实例化DataContractJsonSerializer对象,需要待序列化的对象类型 DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); //把Json传入内存流中保存 MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); // 使用ReadObject方法反序列化成对象 return serializer.ReadObject(stream); }
2,方法2,使用JavaScriptSerializer,建议用这个,通用的Json转对象,上面方法报错,这个方法不报错
1,添加引用
【1.1】引用:System.Web.Extensions.dll
【1.2】using System.Web.Script.Serialization;
2,序列化和反序列化的方法
//JavaScriptSerializer json = new JavaScriptSerializer(); //// 反序列化JSON字符串到对象 //User user = json.Deserialize<User>(jsonString); //// 序列化对象为JSON字符串 //string jsonString = json.Serialize(user);
3,测试:序列化和反序列化
public class ResultItem { public string itemname { get; set; } = "1";//测试:少1个字段,json转对象没问题 public string varname { get; set; } = "Torque"; public string value { get; set; } = "25.01"; }
/// <summary> /// 上传给MES的拧紧结果 /// </summary> public class Physis_MES_AllData { /// <summary> /// 工序编号 /// </summary> public string node_code { get; set; } = "20"; /// <summary> /// 站点编号 /// </summary> public string station_code { get; set; } = "N20S1"; /// <summary> /// 序列号 /// </summary> public string serialno { get; set; } = "D:M201796819474"; /// <summary> /// 员工工号 /// </summary> public string operator_code { get; set; } = ""; /// <summary> /// 员工姓名 /// </summary> public string operator_name { get; set; } = "";//测试:少1个字段,json转对象没问题 //public string operator_name2 { get; set; } = "";//测试:多1个字段,json转对象没问题 /// <summary> /// 拧紧数据 /// </summary> public List<ResultItem> ResultlList { get; set; } = new List<ResultItem>()//测试:少1个字段,json转对象没问题 { new ResultItem(), new ResultItem(), new ResultItem(){itemname = "2",varname = "Angle",value = "88.0"}, new ResultItem(){itemname = "3",varname = "Angle",value = "89.0"}, new ResultItem(){itemname = "4",varname = "TorqueMax",value = "84.0"}, new ResultItem(){itemname = "4",varname = "TorqueMin",value = "85.0"}, }; ///// <summary> ///// 拧紧数据 ///// </summary> //public List<ResultItem> ResultlList2 { get; set; } = new List<ResultItem>()//测试:多1个字段,json转对象没问题 //{ // new ResultItem(), // new ResultItem(), // new ResultItem(){itemname = "2",varname = "Angle",value = "88.0"}, // new ResultItem(){itemname = "3",varname = "Angle",value = "89.0"}, // new ResultItem(){itemname = "4",varname = "TorqueMax",value = "84.0"}, // new ResultItem(){itemname = "4",varname = "TorqueMin",value = "85.0"}, //}; }
#region 序列化和反序列化测试 //测试:Json转对象 private void btn_test_Click(object sender, EventArgs e) { string jsonData = @"{ 'ResultlList':[ {'itemname':'1','value':'25.01','varname':'Torque'}, {'itemname':'1','value':'25.01','varname':'Torque'}, {'itemname':'2','value':'88.0','varname':'Angle'}, {'itemname':'3','value':'89.0','varname':'Angle'}, {'itemname':'4','value':'89.0','varname':'TorqueMax'}, {'itemname':'4','value':'85.0','varname':'TorqueMin'}], 'node_code':'20', 'operator_code':'', 'operator_name':'', 'serialno':'D:M201796819474', 'station_code':'N20S1'}"; //【以下方法:JSON字符串到对象:失败,报错:Physis_MES_AllData 时出现错误。需要标记“"”,但找到“'”。】 //Physis_MES_AllData objectData = new Physis_MES_AllData(); //object c = getObjectByJson(jsonData, objectData); //【以下方法:JSON字符串到对象:成功,建议用以下方法】 JavaScriptSerializer json = new JavaScriptSerializer(); // 反序列化JSON字符串到对象 Physis_MES_AllData objectData = json.Deserialize<Physis_MES_AllData>(jsonData); } //测试:对象转Json private void button4_Click(object sender, EventArgs e) { Physis_MES_AllData data = new Physis_MES_AllData() { }; //【以下方法:对象转JSON:成功】 //string res= getJsonByObject(data); //res结果: //{ "ResultlList":[ // {"itemname":"1","value":"25.01","varname":"Torque"}, // {"itemname":"1","value":"25.01","varname":"Torque"}, // {"itemname":"2","value":"88.0","varname":"Angle"}, // {"itemname":"3","value":"89.0","varname":"Angle"}, // {"itemname":"4","value":"84.0","varname":"TorqueMax"}, // {"itemname":"4","value":"85.0","varname":"TorqueMin"}], // "node_code":"20", // "operator_code":"", // "operator_name":"", // "serialno":"D:M201796819474", // "station_code":"N20S1"} //【以下方法:对象转JSON:成功】 JavaScriptSerializer json = new JavaScriptSerializer(); // 序列化对象为JSON字符串 string res = json.Serialize(data); txt_postResult.Text = res; //res结果: //{ "node_code":"20", // "station_code":"N20S1", // "serialno":"D:M201796819474", // "operator_code":"", // "operator_name":"", // "ResultlList":[ // {"itemname":"1","varname":"Torque","value":"25.01"}, // {"itemname":"1","varname":"Torque","value":"25.01"}, // {"itemname":"2","varname":"Angle","value":"88.0"}, // {"itemname":"3","varname":"Angle","value":"89.0"}, // {"itemname":"4","varname":"TorqueMax","value":"84.0"}, // {"itemname":"4","varname":"TorqueMin","value":"85.0"}]} } #endregion
4,实际应用
1,对象转JSON,客户端提交POST请求
private void btn_post_Click(object sender, EventArgs e) { string url = this.txt_url.Text; TighteningData data=new TighteningData() { Angle = txt_angle.Text, AngleMax = txt_angleMax.Text, AngleMin = txt_angleMin.Text, DeviceName = txt_deviceName.Text, Index = txt_index.Text, ProductName = txt_productName.Text, Pset = txt_pset.Text, SN = txt_sn.Text, TighteningStatus = txt_tighteningStatus.Text, Torque = txt_torque.Text, TorqueMax = txt_torqueMax.Text, TorqueMin = txt_torqueMin.Text }; //string body = $"Angle={data.Angle}&AngleMax={data.AngleMax}&AngleMin={data.AngleMin}&DeviceName={data.DeviceName}&Pset={data.Pset}&SN={data.SN}&TighteningStatus={data.TighteningStatus}&Torque={data.Torque}&TorqueMax={data.TorqueMax}&TorqueMin={data.TorqueMin}&Index={data.Index}&ProductName={data.ProductName}"; //方法【1】:序列化对象为JSON字符串 //string body = getJsonByObject(data); //方法【2】:序列化对象为JSON字符串 JavaScriptSerializer json = new JavaScriptSerializer(); string body = json.Serialize(data); string res = HttpWebRequestPost(url, body); MessageBox.Show(res); }
2,服务端接收POST请求,解析JSON数据
private string HandleRequest(HttpListenerRequest request, HttpListenerResponse response) { string data = null; try { var byteList = new List<byte>(); var byteArr = new byte[2048]; int readLen = 0; int len = 0; //接收客户端传过来的数据并转成字符串类型 do { readLen = request.InputStream.Read(byteArr, 0, byteArr.Length); len += readLen; byteList.AddRange(byteArr); } while (readLen != 0); data = Encoding.UTF8.GetString(byteList.ToArray(), 0, len); //获取得到数据data可以进行其他操作 } catch (Exception ex) { response.StatusDescription = "404"; response.StatusCode = 404; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"在接收数据时发生错误:{ex.ToString()}"); return $"在接收数据时发生错误:{ex.ToString()}";//把服务端错误信息直接返回可能会导致信息不安全,此处仅供参考 } response.StatusDescription = "200";//获取或设置返回给客户端的 HTTP 状态代码的文本说明。 response.StatusCode = 200;// 获取或设置返回给客户端的 HTTP 状态代码。 Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"接收数据完成:{data.Trim()},时间:{DateTime.Now.ToString()}"); JavaScriptSerializer js = new JavaScriptSerializer(); //实例化一个能够序列化数据的类 RequestDataModel requestDataModel = js.Deserialize<RequestDataModel>(data); if (DataTriggerEvent != null) { DataTriggerEvent(requestDataModel); } return $"接收数据完成"; }