【问题标题】:Json deserialize is not workingJson反序列化不起作用
【发布时间】: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 变量中得到反序列化的结果。

【问题讨论】:

标签: c# .net json


【解决方案1】:

你可以这样做

ResultOrder obj = response.Content.ReadAsAsync<ResultOrder>()

直接。这将为您处理反序列化。

【讨论】:

    【解决方案2】:

    为了反序列化 newOrder 对象,您需要进行以下更改。

    ResultOrder obj = JsonConvert.DeserializeObject<ResultOrder>(newOrder);
    

    在反序列化对象时,在您的情况下转换为期望对象 ResultOrder

    【讨论】:

      猜你喜欢
      • 2013-01-30
      • 2023-04-06
      • 2015-09-28
      • 2020-03-10
      • 2012-07-11
      • 2019-01-21
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      相关资源
      最近更新 更多