Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading HttpwebResponse json response, C#

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.

like image 898
tugberk Avatar asked Mar 31 '11 00:03

tugberk


2 Answers

First you need an object

public class MyObject {   public string Id {get;set;}   public string Text {get;set;}   ... } 

Then in here

    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

like image 137
Jason Watts Avatar answered Oct 01 '22 09:10

Jason Watts


I'd use RestSharp - https://github.com/restsharp/RestSharp

Create class to deserialize to:

public class MyObject {     public string Id { get; set; }     public string Text { get; set; }     ... } 

And the code to get that object:

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; 

Check out http://restsharp.org/ to get started.

like image 22
Ben Cull Avatar answered Oct 01 '22 09:10

Ben Cull