方法1,通用方法,以下方法是转载别人的
1,添加引用
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,使用JavaScriptSerializer
1,添加引用
2,方法
//JavaScriptSerializer json = new JavaScriptSerializer(); //// 反序列化JSON字符串到对象 //User user = json.Deserialize<User>(jsonString); //// 序列化对象为JSON字符串 //string jsonString = json.Serialize(user);
3,实际应用
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 $"接收数据完成"; }