【发布时间】:2018-02-27 06:20:55
【问题描述】:
我收到来自 API 的 Json 响应,但无法转换为对象。
我的课是
public class ResultOrder
{
public int id { get; set; }
public string currency { get; set; }
public string status { get; set; }
public string order_id { get; set; }
public double price { get; set; }
}
var response = await client.PostAsync(path, body);
if (response.IsSuccessStatusCode)
{
var newOrder = await response.Content.ReadAsAsync<dynamic>();
ResultOrder obj = JsonConvert.DeserializeObject(newOrder);
}
我在变量 newOrder 中从 API 得到的结果是 --
{
"id": 68456,
"currency": "USD",
"status": "pending",
"price": "79.97",
"order_id": "1233219",
}
但是无法在 obj 变量中得到反序列化的结果。
【问题讨论】:
-
与Unable to cast object of type Newtonsoft.Json.Linq.JObject even though I am trying to cast to an object with matching properties 中的问题几乎相同。解决方法也是一样的,即使用泛型的、类型化的反序列化方法:
JsonConvert.DeserializeObject<ResultOrder>(jsonString); -
为什么不直接做
response.Content.ReadAsAsync<ResultOrder>()? -
@ADyson,请写下您的评论作为答案,这样我就可以投票给您并使其成为可接受的答案。谢谢老兄。