[c#] 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.

This question is related to c# json rest httpwebrequest httpwebresponse

The answer is


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.


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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to rest

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Returning data from Axios API Access Control Origin Header error using Axios in React Web throwing error in Chrome JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to send json data in POST request using C# How to enable CORS in ASP.net Core WebAPI RestClientException: Could not extract response. no suitable HttpMessageConverter found REST API - Use the "Accept: application/json" HTTP Header 'Field required a bean of type that could not be found.' error spring restful API using mongodb MultipartException: Current request is not a multipart request

Examples related to httpwebrequest

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send How to properly make a http web GET request Send JSON via POST in C# and Receive the JSON returned? How to create JSON post to api using C# Use C# HttpWebRequest to send json to web service Post form data using HttpWebRequest HttpWebRequest-The remote server returned an error: (400) Bad Request Get host domain from URL? How to ignore the certificate check when ssl Receiving JSON data back from HTTP request

Examples related to httpwebresponse

How to convert WebResponse.GetResponseStream return into a string? How to get error information when HttpWebRequest.GetResponse() fails reading HttpwebResponse json response, C# Uses of content-disposition in an HTTP response header