c#从Web Service 获取信息并解析json

如果需要登录,使用下边方法,如果为匿名登录的,可以省略,在全局变量中定义public static string Cookiemsg,方便重复使用cookie。

 1 public static CookieMsg GetCookieMessage(string name, string password)
 2  {
 3                 CookieMsg cookieMsg = null;
 4                 string retString = "";
 5                 try
 6                 {
 7                     HttpWebRequest request = (HttpWebRequest)WebRequest.Create("&user=" + name + "&pwd=" + password);
 8     
 9                     request.Method = "GET";
10                   request.ContentType = "text/html;charset=UTF-8";
11                   HttpWebResponse response = (HttpWebResponse)request.GetResponse();
12   
13                   Stream myResponseStream = response.GetResponseStream();
14                   StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
15                   retString = myStreamReader.ReadToEnd();
16   
17                   myStreamReader.Close();
18                   myResponseStream.Close();
19  
20                   cookieMsg = ManageCookieMsg(retString);
21               }
22               catch (Exception ex)
23               {
24   
25               }
26   
27               return cookieMsg;
28 }
29 
30 
31         private static CookieMsg ManageCookieMsg(string json)
32         {
33 
34             MemoryStream stream2 = new MemoryStream();
35             DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(CookieMsg));
36             StreamWriter wr = new StreamWriter(stream2);
37             CookieMsg cookieMsg = null;
38             try
39             {
40                 wr.Write(json);
41                 wr.Flush();
42                 stream2.Position = 0;
43                 Object obj = ser2.ReadObject(stream2);
44                 cookieMsg = (CookieMsg)obj;
45 
46                 Cookiemsg = "person_id=" + cookieMsg.Person_id + ";" + "identity_id=" + cookieMsg.Identity + ";" + "token=" + cookieMsg.Token;
47             }
48             catch (Exception ex)
49             {
50 
51             }
52 
53             return cookieMsg;
54         }


需要另一个类中添加封装Json的属性,会将返回的用户信息封装在一个类中。

 1 using System.Collections.Generic;
 2 using System.Runtime.Serialization;   
 3 
 4  #region Cookie
 5 
 6     [DataContract]
 7     public class CookieMsg
 8     {
 9         [DataMember]
10         private string person_id;
11 
12         public string Person_id
13         {
14             get { return person_id; }
15             set { person_id = value; }
16         }
17 
18         [DataMember]
19         private string person_name;
20 
21         public string Person_name
22         {
23             get { return person_name; }
24             set { person_name = value; }
25         }
26 
27         [DataMember]
28         private string identity;
29 
30         public string Identity
31         {
32             get { return identity; }
33             set { identity = value; }
34         }
35 
36         [DataMember]
37         private string token;
38 
39         public string Token
40         {
41             get { return token; }
42             set { token = value; }
43         }
44 
45     }
46 
47 #endregion


下面开始拼装Http的头,获取所需信息。

 1         private static string WebMessage(string url)
 2         {
 3             string retString = "";
 4             try
 5             {
 6 
 7                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
 8                 request.Method = "GET";
 9                 request.Accept = "application/json, text/javascript, */*; q=0.01";
10                 request.ContentType = "application/x-www-form-urlencoded";
11                 request.Proxy = null;
12                 request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
13                 request.Timeout = 1000;
14                 request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36";
15                 request.KeepAlive = true;
16                 request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
17                 request.Headers.Add("Cookie", Cookiemsg);
18 
19                 ////填充参数
20                 byte[] param;
21                 StringBuilder sb = new StringBuilder();
22                 param = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
23                 request.ContentLength = param.Length;
24 
25                 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
26 
27 
28                 Stream myResponseStream = response.GetResponseStream();
29                 if (response.ContentEncoding.ToLower().Contains("gzip"))
30                 {
31 
32                     myResponseStream = new GZipStream(myResponseStream, CompressionMode.Decompress);
33                 }
34                 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
35 
36                 retString = myStreamReader.ReadToEnd();
37 
38                 myStreamReader.Close();
39                 myResponseStream.Close();
40 
41             }
42             catch (Exception ex)
43             {
44 
45             }
46             return retString;
47         }

返回的Json字符串再使用上面的封装方法,按照实际返回信息进行封装就可以了。

转载于:https://www.cnblogs.com/MyFirstBlog/p/3847949.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#解析JSON数据可以使用Newtonsoft.Json库。这个库可以将JSON数据转换成.NET对象,或者将.NET对象转换成JSON数据。 以下是一个例子,展示如何解析JSON数据并获取其中的值: ```csharp using Newtonsoft.Json.Linq; // json是一个包含JSON数据的字符串 string json = "{ \"name\": \"John\", \"age\": 30 }"; // 将JSON数据转换成JObject对象 JObject obj = JObject.Parse(json); // 从JObject对象中获取值 string name = (string)obj["name"]; int age = (int)obj["age"]; ``` 首先,使用JObject.Parse方法将JSON数据转换成JObject对象。然后,使用索引器访问对象的属性并强制转换为需要的类型。 当然,如果你知道JSON数据结构的具体格式,还可以使用反序列化来将JSON数据转换成.NET对象。这种方法更加方便,因为你可以直接使用.NET对象的属性和方法来访问数据。 以下是一个例子,展示如何使用反序列化来解析JSON数据: ```csharp using Newtonsoft.Json; // 定义一个.NET类来表示JSON数据的结构 public class Person { public string Name { get; set; } public int Age { get; set; } } // json是一个包含JSON数据的字符串 string json = "{ \"name\": \"John\", \"age\": 30 }"; // 将JSON数据反序列化成Person对象 Person person = JsonConvert.DeserializeObject<Person>(json); // 访问Person对象的属性 string name = person.Name; int age = person.Age; ``` 这个例子中,我们定义了一个Person类来表示JSON数据的结构。然后,使用JsonConvert.DeserializeObject方法将JSON数据反序列化成Person对象。最后,通过访问Person对象的属性来获取数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值