我有这样的代码:
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");
}
}
但我在行
收到错误var Samochod = response.Content.ReadAsAsync<Samochod>().Result;
我可以将Json对象从HttpResponseMessage
响应转换为字符串吗?我试图这样做:
string value = response.ToString();
但这是胡说八道。我必须知道我从Web API收到的Json文件中有什么内容。之后我会知道如何修复错误。
编辑:
问题是,当我放置&#34; localhost:8080 / api / values / 1&#34;直接进入浏览器,输出是:
{"CarID":1,"Marka":"Daewoo","Model":"Lanos","Kolor":"Zielony"`
,但是当我通过Win Form应用程序执行此操作时,我正在接受:
\"{\"CarID\":1,\"Marka\":\"Daewoo\",\"Model\":\"Lanos\",\"Kolor\":\"Zielony\"}\"
错误:&#34;类型&#39; System.AggregateException&#39;的第一次机会异常发生在mscorlib.dll中。视图细节中的内部异常:
{"Error converting value \"{\"CarID\":1,\"Marka\":\"Daewoo\",\"Model\":\"Lanos\",\"Kolor\":\"Zielony\"}\" to type 'WebAPIwinForms.Samochod'. Path '', line 1, position 78."}
答案 0 :(得分:1)
你应该使用ReadAsStringAsync()方法转换字符串然后反序列化到你的对象,例如:
var Samochod = response.Content.ReadAsStringAsync();