32

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.

yizzlez
  • 8,757
  • 4
  • 29
  • 44
tugberk
  • 57,477
  • 67
  • 243
  • 335
  • 1
    It might be a good idea to check out Restsharp to do your rest service calls https://github.com/johnsheehan/RestSharp/wiki/Getting-Started will make your life 100000x easier down the track, and you can setup object models for it to decode to. – anthonyvscode Mar 31 '11 at 00:24
  • @anthonyvscode the wiki/get-started moved to here https://github.com/restsharp/RestSharp/wiki/Getting-Started – jaybro Oct 14 '19 at 20:27

3 Answers3

58

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

Community
  • 1
  • 1
Jason Watts
  • 3,800
  • 29
  • 33
  • thanks for the reply. honestly, I was a bit lazy for this question. couple of months ago, I have created a wrapper for Google URL Shortener API and I used System.Web.Extensions library for that too. – tugberk Mar 31 '11 at 07:42
  • i have tried your code but gives error "No overload method 'Deserialize' take '2' arguments" do i miss something? – SHEKHAR SHETE Jun 16 '14 at 08:46
  • This code is over 3 years old. There are probably better ways to do this now. I also don't know what version of the JavaScriptSerializer that was. It may have changed? – Jason Watts Jul 01 '14 at 15:23
  • Hey I revive the thread... if we have an array of array of string.. what is the object structure for that? – Jean-philippe Emond Aug 05 '16 at 17:49
  • 4
    I would recommend using [Json.Net](http://www.newtonsoft.com/json/help/html/jsonnetvsdotnetserializers.htm) to serialize the Json to an object over `JavaScriptSerializer`. It's more efficent and is now recommended by microsoft for this kind of work over it's own seriaializer. – Liam Dec 21 '16 at 10:04
  • var myobj = js.Deserialize(objText); – Yves Rochon Mar 14 '18 at 19:39
13

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.

Steve Wranovsky
  • 5,503
  • 4
  • 34
  • 52
Ben Cull
  • 9,434
  • 7
  • 43
  • 38
0

If you're getting source in Content Use the following method

try
{
    var response = restClient.Execute<List<EmpModel>>(restRequest);

    var jsonContent = response.Content;

    var data = JsonConvert.DeserializeObject<List<EmpModel>>(jsonContent);

    foreach (EmpModel item in data)
    {
        listPassingData?.Add(item);
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Data get mathod problem {ex} ");
}
adiga
  • 34,372
  • 9
  • 61
  • 83
logeshpalani31
  • 1,416
  • 12
  • 33