Shagohad
Shagohad

Reputation: 395

Convert Json from HttpResponseMessage to string

I've got code like this:

 private void button1_Click(object sender, EventArgs e)
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:8080/");
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage response = client.GetAsync("api/values/1").Result;
        if (response.IsSuccessStatusCode)
        {
            var Samochod = response.Content.ReadAsAsync<Samochod>().Result;
            MessageBox.Show("Car ID: " + Samochod.CarID + ", Car Brand: " + Samochod.Marka);
        }
        else
        {
            MessageBox.Show("False");
        }
    }

but I'm receiving error in line

var Samochod = response.Content.ReadAsAsync<Samochod>().Result;

Can I convert a Json object from HttpResponseMessage response to a string? I was trying to do:

string value = response.ToString();

But it's nonsense. I have to know what is in Json file I'm receiving from Web API. After that I will know, how to fix error.

Edit:

The problem is, when I'm putting "localhost:8080/api/values/1" directly into browsers, the output is:

{"CarID":1,"Marka":"Daewoo","Model":"Lanos","Kolor":"Zielony"`

, but when I'm doing this by Win Form application, I'm receing:

\"{\"CarID\":1,\"Marka\":\"Daewoo\",\"Model\":\"Lanos\",\"Kolor\":\"Zielony\"}\" 

And error: "A first chance exception of type 'System.AggregateException' occurred in mscorlib.dll. And Inner Exception in View detail:

{"Error converting value \"{\"CarID\":1,\"Marka\":\"Daewoo\",\"Model\":\"Lanos\",\"Kolor\":\"Zielony\"}\" to type 'WebAPIwinForms.Samochod'. Path '', line 1, position 78."}

Upvotes: 1

Views: 21379

Answers (2)

babak jafari
babak jafari

Reputation: 32

Instead of the following line:

var Samochod = response.Content.ReadAsAsync<Samochod>().Result;

Please make sure you have installed Newtonsoft.Json, and then update your code as follows:

var Samochod = JsonConvert.DeserializeObject<Samochod>(await response.Content.ReadAsStringAsync());

Alternatively, you can utilize the following line, which is an extension method from the System.Net.Http.Json library:

var Samochod = await response.Content.ReadFromJsonAsync<Samochod>();

To enable the above-mentioned line of code to execute, you need to modify your method to be asynchronous, as demonstrated below:

private async void button1_Click(object sender, EventArgs e)

Finally, your code should appear like below:

private async void button1_Click(object sender, EventArgs e)
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:8080/");
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    HttpResponseMessage response = await client.GetAsync("api/values/1");
    if (response.IsSuccessStatusCode)
    {
        var Samochod = JsonConvert.DeserializeObject<Samochod>(await response.Content.ReadAsStringAsync());
        MessageBox.Show("Car ID: " + Samochod.CarID + ", Car Brand: " + Samochod.Marka);
    }
    else
    {
        MessageBox.Show("False");
    }
}

Upvotes: 0

MehDi NicKhoo
MehDi NicKhoo

Reputation: 41

you should use ReadAsStringAsync() method to convert string then deserialize to your object for example :

var Samochod = response.Content.ReadAsStringAsync();

Upvotes: 2

Related Questions