C#字符串转成JSON对象,并解析出里面的数据
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#字符串转成JSON对象,并解析出里面的数据相关的知识,希望对你有一定的参考价值。
代码如下:
_Cookie = new CookieCollection();
HttpWebRequest request = HttpWebResponseUtility.CreateGetHttpRequest(_serverUrl, null, null, _Cookie);
//request.CookieContainer = _Cookie;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
try
StreamReader stream = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string boday = stream.ReadToEnd();
Object obj = JsonConvert.DeserializeObject(boday);
//JObject obj = (JObject)RequestHelper.getData(boday);
MessageBox.Show("W");
/*
if (obj != null && obj["uid"] != null && obj["uid"].ToString().Equals("1"))
BeginInvoke(new ShowFrom(LoginHandle));
else
BeginInvoke(new ShowFrom(delegate() MessageBox.Show("用户名或密码错误"); ));
* */
catch
catch
MessageBox.Show("出错");
Object obj = JsonConvert.DeserializeObject(boday);这句程序无法运行,不知道应该怎么做才能让返回流中的字符串变成JSON对象,并且解析里面的数据来做判断是否登陆
构造对象:
public struct ToJsonMy
public string result get; set; //属性的名字,必须与json格式字符串中的"key"值一样。
public string res_info get; set;
public string queryorder_info get; set;
转换过程:
public static void JsonMy()
string json = Jsonstr("D:\\\\json\\\\jsonmy1.txt");//Jsonstr函数读取json数据的文本txt
javascriptSerializer js = new JavaScriptSerializer(); //实例化一个能够序列化数据的类
ToJsonMy list = js.Deserialize<ToJsonMy>(json); //将json数据转化为对象类型并赋值给list
string result = list.result;
string res_info = list.res_info;
string queryorder_info = list.res_info;
json包含对象数组 json数据:jsonmy4.txt
"result":"0","res_info":"ok","queryorder_info":"order_num":"5","orderdetail":["CFTUin":"769839263","CancelDeadline":"2013-09-12 23:00:00","CheckInDate":"2013-09-12 00:00:00","CheckOutDate":"2013-09-13 00:00:00","CityID":"0101","CurrencyCode":"RMB","HotelID":"00301105","HotelName":"乐家连锁(北京天坛南门店)(原速8酒店(北京天坛南店)",
"ListID":"1000000005201308280002999652","PayAmt":"228","PayType":"0","RommsCnt":"1","SPTransID":"65202157","State":"4","CFTUin":"248486133","CancelDeadline":"2013-10-13 23:00:00","CheckInDate":"2013-10-13 00:00:00","CheckOutDate":"2013-10-18 00:00:00","CityID":"0201","CurrencyCode":"RMB","HotelID":"10201314","HotelName"
"ListID":"1000000005201308280002999413","PayAmt":"1140","PayType":"0","RommsCnt":"1","SPTransID":"65197226","State":"4"]
参考技术A 你要先分析boday 这个字符串,先去确认它是不是个json格式的数据,然后根据它的结构创建一个相应的类(假设叫XXX类),之后才能进行json的解析:XXX xxx=JsonConvert.DeserializeObject<XXX>(boday);本回答被提问者采纳 参考技术B JavascriptSerializble 参考技术C 给你一个网址,你看下如何转化的。http://www.cnblogs.com/sun-sjmeng/archive/2012/09/08/2660559.html 参考技术D 可考虑使用第三方dll:NewtonSoft.Json.dll
以上是关于C#字符串转成JSON对象,并解析出里面的数据的主要内容,如果未能解决你的问题,请参考以下文章