0

I am receiving a Json response from an API but unable to convert to object.

My class is

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);          
}

And the result i am getting from API in the variable newOrder is --

{
  "id": 68456,
  "currency": "USD",
  "status": "pending",
  "price": "79.97",
  "order_id": "1233219",
}

But unable to get the deserialized result in the obj variable.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Sam
  • 9
  • 9
  • Pretty much the same problem as in [Unable to cast object of type Newtonsoft.Json.Linq.JObject even though I am trying to cast to an object with matching properties](https://stackoverflow.com/q/48130753/3744182). The solution is also the same, namely to use the generic, typed deserialization method: `JsonConvert.DeserializeObject(jsonString);` – dbc Feb 27 '18 at 06:24
  • Why not just do `response.Content.ReadAsAsync()` directly? – ADyson Feb 27 '18 at 06:24
  • @ADyson, plz write your comment as an answer so i could vote you and make it as acceptable answer. Thanks mate. – Sam Feb 27 '18 at 06:50

2 Answers2

1

You can just do

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

directly. This will handle the deserialisation for you.

ADyson
  • 57,178
  • 14
  • 51
  • 63
0

Following changes you need to do to deserialize the newOrder object.

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

While deserializing the object, cast to desire object in your case it is ResultOrder

enter image description here