JSON解析
static void Main(string[] args)
{
string serviceAddress = “http://20148414.dianpu.lianjia.com/shop/ershoufang/?p=1&type=1”;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
request.Method = “GET”;
request.ContentType = “text/xml;charset=UTF-8”;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
string json = JsonHelper.JsonSerializer(retString);
Console.Write(json);
}
public static string JsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
string jsonData = jsonString;
JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
jsonData = jsonSerialize.Deserialize<T>(jsonString).ToString();
ms.Close();
return jsonData;
}
不知道怎么办了!
想要提取JSON里的信息。
static void Main(string[] args)
{
string serviceAddress = “http://20148414.dianpu.lianjia.com/shop/ershoufang/?p=1&type=1”;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
request.Method = “GET”;
request.ContentType = “text/xml;charset=UTF-8”;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
string json = JsonHelper.JsonSerializer(retString);
Console.Write(json);
}
public static string JsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
string jsonData = jsonString;
JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
jsonData = jsonSerialize.Deserialize<T>(jsonString).ToString();
ms.Close();
return jsonData;
}
不知道怎么办了!
想要提取JSON里的信息。
解决方案
20
jsonData = jsonSerialize.Deserialize<T>(jsonString).ToString();
你反序列化之后又转成string是什么鬼?
直接return jsonSerialize.Deserialize<T>(jsonString)出去不就行了吗?
你反序列化之后又转成string是什么鬼?
直接return jsonSerialize.Deserialize<T>(jsonString)出去不就行了吗?
20
本人非常喜欢的写法。就是用dynamic 类型。
dynamic obj = jsonSerialize.Deserialize<dynamic>(jsonString); //例如他有一个Name属性。 string name = obj.Name;//这样就ok了。不过假如没有这个属性。会报错,假如能肯定获取的数据没问题,就不加验证也可以。
本人就喜欢这样写。很方便。你就当传过来的是一个对象这么用就行了。