0

I am testing APIs and currently, I am testing a Post method that returns a Long data type Id. I have created a C# object class, where I also have other properties that it will return from another API call. For now, this Post call only returns an Id and I want to Map it to the Id property in my class but I get an exception Could not cast or convert from System.Int64 to Model class

// Here is my model class

public class Model
{
  public long id { get; set; }
  public string name { get; set; }
  public long type { get; set; }
}

// Here is the call I am making.. FYI I am using RestSharp
response = HttpPost("URl");
var id =  JsonConvert.DeserializeObject<Model.id>(restResponse.Content); //How can I map just the Id.

My response from the API is a long data type ex: 658

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
KevinDavis965
  • 39
  • 1
  • 8

2 Answers2

1

Replace Model.id by long.

JsonConvert.DeserializeObject<long>

You can set it like this

Model model = new Model();
model.id = JsonConvert.DeserializeObject<long>...
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
0

You may adapt this example to your model.

using (var client = new HttpClient())
{
  string url = string.Format("your-api-url");
  var response = client.GetAsync(url).Result;

  string responseAsString = await response.Content.ReadAsStringAsync();
  result = JsonConvert.DeserializeObject<YourModel>(responseAsString);
}

public class YourModel
{
   [JsonProperty("confirmed")]
   public ValueModel Confirmed { get; set; }
   [JsonProperty("recovered")]
   public ValueModel Recovered { get; set; }
   [JsonProperty("values")]
   public ValueModel Values { get; set; }
}

public class ValueModel
{
   [JsonProperty("value")]
   public int Value { get; set; }
}
fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88