本文介绍了阅读HttpwebResponse JSON响应,C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的应用程序之一,我正在从WebRequest的响应。这项服务是RESTful服务,将返回类似下面的JSON格式的结果是:
In one of my apps, I am getting the response from a webrequest. The service is Restful service and will return a result similar to the JSON format below:
{
"id" : "1lad07",
"text" : "test",
"url" : "http:\/\/twitpic.com\/1lacuz",
"width" : 220,
"height" : 84,
"size" : 8722,
"type" : "png",
"timestamp" : "Wed, 05 May 2010 16:11:48 +0000",
"user" : {
"id" : 12345,
"screen_name" : "twitpicuser"
}
}
和这里是我当前的代码:
and here is my current code:
byte[] bytes = Encoding.GetEncoding(contentEncoding).GetBytes(contents.ToString());
request.ContentLength = bytes.Length;
using (var requestStream = request.GetRequestStream()) {
requestStream.Write(bytes, 0, bytes.Length);
using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {
using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {
//What should I do here?
}
}
}
我怎样才能读取响应?我想要的网址和用户名。
How can I read the response? I want the url and the username.
推荐答案
首先,你需要一个对象
public class MyObject {
public string Id {get;set;}
public string Text {get;set;}
...
}
然后在这里
using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {
using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
}
}
我还没有与测试分层对象你有,但是这应该给你访问到你想要的属性。
I haven't tested with the hierarchical object you have, but this should give you access to the properties you want.
的JavaScriptSerializer System.Web.Script.Serialization
JavaScriptSerializer System.Web.Script.Serialization
这篇关于阅读HttpwebResponse JSON响应,C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!