• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#处理JSON常用的帮助类

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

C#请求接口的方法,具体代码:

首先需要添加引用和第三方的组件,具体如下:

引用命名空间:

1 using System.IO;
2 using Newtonsoft.Json.Linq;
3 using System.Web.Script.Serialization; 

常用到的两种请求方式的代码类,具体实现如下

 1         /// <summary>
 2         /// Post 带有参数请求Json的方法
 3         /// </summary>
 4         /// <param name="PARAMETER">请求的参数</param>
 5         /// <param name="POSTURL">请求的URL地址</param>
 6         /// <returns>返回json字符串</returns>
 7         public static JObject RequestJsonByUrlPost(string PARAMETER, string POSTURL)
 8         {
 9             JObject jo = new JObject();
10             try
11             {
12                 UTF8Encoding encoding = new UTF8Encoding();
13                 byte[] data = encoding.GetBytes(PARAMETER);
14                 HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(POSTURL);
15                 myRequest.Method = "Post";
16                 myRequest.ContentType = "application/x-www-form-urlencoded";
17                 myRequest.ContentLength = data.Length;
18                 Stream newStream = myRequest.GetRequestStream();
19                 newStream.Write(data, 0, data.Length);
20                 newStream.Close();
21                 HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
22                 StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
23                 string sJson = reader.ReadToEnd();
24                 jo = JObject.Parse(sJson);
25             }
26             catch (Exception ex)
27             {
28                 MessageUtil.ShowException("系统错误,请联系管理员!", ex);
29             }
30             return jo;
31         }
32         /// <summary>
33         /// Get 请求的方法
34         /// </summary>
35         /// <param name="geturl">请求的URL地址</param>
36         /// <returns>返回json字符串</returns>
37         public static JObject RequestJsonByUrlGet(string geturl)
38         {
39             JObject jo = new JObject();
40             try
41             {
42                 HttpWebRequest http = WebRequest.Create(geturl) as HttpWebRequest;
43                 HttpWebResponse response = (HttpWebResponse)http.GetResponse();
44                 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
45 
46                 string sJson = reader.ReadToEnd();
47                 http.Abort();
48                 ArrayList ObjList = new ArrayList();
49                 //将字符串转换成Json对象
50                 jo = JObject.Parse(sJson);
51             }
52             catch (Exception ex)
53             {
54                 MessageUtil.ShowException("系统错误,请联系管理员!", ex);
55             }
56             return jo;
57         }

处理接口返回的 JSON 数据转换常用的帮助类,具体代码如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace HackMoney
 7 {
 8     public class JsonHelper
 9     {
10 
11         /// <summary>
12         /// 转换对象为JSON格式数据
13         /// </summary>
14         /// <typeparam name="T"></typeparam>
15         /// <param name="obj">对象</param>
16         /// <returns>字符格式的JSON数据</returns>
17         public static string GetJSON<T>(object obj) {
18             string result = String.Empty;
19             try {
20                 System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
22                 using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
23                     serializer.WriteObject(ms, obj);
24                     result = System.Text.Encoding.UTF8.GetString(ms.ToArray());
25                 }
26             } catch (Exception ex) {
27                 throw ex;
28             }
29             return result;
30         }
31         /// <summary>
32         /// 转换List<T>的数据为JSON格式
33         /// </summary>
34         /// <typeparam name="T"></typeparam>
35         /// <param name="vals">列表值</param>
36         /// <returns>JSON格式数据</returns>
37         public static string JSON<T>(List<T> vals) {
38             System.Text.StringBuilder st = new System.Text.StringBuilder();
39             try {
40                 System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
41 
42                 foreach (T city in vals) {
43                     using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
44                         s.WriteObject(ms, city);
45                         st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
46                     }
47                 }
48             } catch (Exception ex) {
49                 throw ex;
50             }
51 
52             return st.ToString();
53         }
54         /// <summary>
55         /// JSON格式字符转换为T类型的对象
56         /// </summary>
57         /// <typeparam name="T"></typeparam>
58         /// <param name="jsonStr"></param>
59         /// <returns></returns>
60         public static T ParseFormByJson<T>(string jsonStr) {
61             T obj = Activator.CreateInstance<T>();
62             using (System.IO.MemoryStream ms =
63             new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonStr))) {
64                 System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
65                 new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
66                 return (T)serializer.ReadObject(ms);
67             }
68         }
69 
70 
71 
72 
73         public static string JSON1<SendData>(List<SendData> vals) {
74             System.Text.StringBuilder st = new System.Text.StringBuilder();
75             try {
76                 System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(SendData));
77 
78                 foreach (SendData city in vals) {
79                     using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
80                         s.WriteObject(ms, city);
81                         st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
82                     }
83                 }
84             } catch (Exception ex) {
85                 throw ex;
86             }
87 
88             return st.ToString();
89         }
90 
91     }
92 }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#WinForm拖动无边框窗体改变无边框窗体尺寸发布时间:2022-07-10
下一篇:
C#Textbox始终保持最后最后一行发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap