简体   繁体   中英

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."}

您应该使用ReadAsStringAsync()方法转换字符串,然后反序列化为您的对象,例如:

var Samochod = response.Content.ReadAsStringAsync();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM