博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
json 序列化的两种方式
阅读量:5743 次
发布时间:2019-06-18

本文共 2564 字,大约阅读时间需要 8 分钟。

JavaScriptSerializer Serializer = new JavaScriptSerializer();ResultData
resultModel_Login = Serializer.Deserialize
>(result_Login);///
/// Get方法/// ///
url地址///
数据 格式为"aa=xx&bb=xxx"///
请求结果
public static string HttpGetConnectToServer(string serverUrl, string postData){//创建请求 var request = (HttpWebRequest)HttpWebRequest.Create(serverUrl + "?" + postData);request.Method = "GET";//设置上传服务的数据格式 request.ContentType = "application/x-www-form-urlencoded";//请求的身份验证信息为默认 request.Credentials = CredentialCache.DefaultCredentials;//请求超时时间 request.Timeout = 10000;//读取返回消息 string res = "";try{var response = (HttpWebResponse)request.GetResponse();var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);res = reader.ReadToEnd();reader.Close();}catch (Exception ex){}return res;}///
/// post方法/// ///
url地址///
提交的ParamData对象///
public static string PostWebRequest
(string postUrl, T paramData){string ret = string.Empty;try{string str_Tem = JsonSerializer(paramData);//将对象转成json串byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(str_Tem);HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));webReq.Method = "POST";webReq.ContentType = " application/json; charset=utf-8";webReq.ContentLength = byteArray.Length;Stream newStream = webReq.GetRequestStream();newStream.Write(byteArray, 0, byteArray.Length);//写入参数newStream.Close();HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);ret = sr.ReadToEnd();sr.Close();response.Close();newStream.Close();}catch (Exception ex){}return ret;}///
/// C#反序列化JSON/// ///
返回类型
///
JSON字符串///
public static T JsonDeserialize
(string strJson){DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson));T objT = (T)ser.ReadObject(ms);ms.Close();return objT;}///
/// C#序列化JSON/// ///
序列化对象类型
///
序列化对象///
public static string JsonSerializer
(T objT){DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));MemoryStream ms = new MemoryStream();ser.WriteObject(ms, objT);string jsonString = Encoding.UTF8.GetString(ms.ToArray());ms.Close();return jsonString;}

 

转载于:https://www.cnblogs.com/muxueyuan/p/4462593.html

你可能感兴趣的文章