阅读HttpwebResponse json响应,C#

tug*_*erk 27 c# rest json httpwebrequest httpwebresponse

在我的一个应用程序中,我收到了webrequest的回复.该服务是Restful服务,将返回类似于以下JSON格式的结果:

{
    "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"
    }
}   
Run Code Online (Sandbox Code Playgroud)

这是我目前的代码:

    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?

            }

        }

    }
Run Code Online (Sandbox Code Playgroud)

我该如何阅读回复?我想要网址和用户名.

Jas*_*tts 54

首先你需要一个物体

public class MyObject {
  public string Id {get;set;}
  public string Text {get;set;}
  ...
}
Run Code Online (Sandbox Code Playgroud)

然后在这里

    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));
        }

    }
Run Code Online (Sandbox Code Playgroud)

我没有使用您拥有的分层对象进行测试,但这可以让您访问所需的属性.

JavaScriptSerializer System.Web.Script.Serialization

  • 我建议使用[Json.Net](http://www.newtonsoft.com/json/help/html/jsonnetvsdotnetserializers.htm)通过`JavaScriptSerializer`将Json序列化为一个对象.它更有效率,现在微软推荐这种类型的工作,而不是它自己的seriaializer. (4认同)

Ben*_*ull 12

我使用RestSharp - https://github.com/restsharp/RestSharp

创建要反序列化的类:

public class MyObject {
    public string Id { get; set; }
    public string Text { get; set; }
    ...
}
Run Code Online (Sandbox Code Playgroud)

以及获取该对象的代码:

RestClient client = new RestClient("http://whatever.com");
RestRequest request = new RestRequest("path/to/object");
request.AddParameter("id", "123");

// The above code will make a request URL of 
// "http://whatever.com/path/to/object?id=123"
// You can pick and choose what you need

var response = client.Execute<MyObject>(request);

MyObject obj = response.Data;
Run Code Online (Sandbox Code Playgroud)

查看http://restsharp.org/即可开始使用.