[英]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? 我可以将Json对象从
HttpResponseMessage
响应转换为字符串吗? 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.
我必须知道我从Web API接收到的Json文件中包含什么。 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: 问题是,当我将“ localhost:8080 / api / values / 1”直接放入浏览器时,输出为:
{"CarID":1,"Marka":"Daewoo","Model":"Lanos","Kolor":"Zielony"`
, but when I'm doing this by Win Form application, I'm receing: ,但是当我通过Win Form应用程序执行此操作时,我收到了:
\"{\"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: 错误:“ mscorlib.dll中发生类型'System.AggregateException'的第一次机会异常。并且在视图详细信息中存在内部异常:
{"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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.