I have an API request in my web application but every time I convert the response result to deserialize object it gives null value to my model.
Here's my code:
var contents = await responseMessage.Content.ReadAsStringAsync();
var statusInfo = responseMessage.StatusCode.ToString();
if (statusInfo == "OK")
{
var jsonresult = JObject.Parse(contents);
var respond = jsonresult["data"].ToString();
var result = JsonConvert.DeserializeObject<ResponseModel>(respond);
}
The contents value is
"{\"data\":{\"totalcount:\":8113,\"tpa:\":6107,\"tip:\":5705},\"message\":\"success\"}"
The respond value is
"{ \r\n"totalcount:\": 8113,\r\n \"tpa:\": 6107,\r\n \"tip:\": 5705\r\n}"
and my model is
public class ResponseModel
{
[JsonProperty(PropertyName = "totalcount")]
public int totalcount { get; set; }
[JsonProperty(PropertyName = "tpa")]
public int tpa { get; set; }
[JsonProperty(PropertyName = "tip")]
public int tip { get; set; }
}
Please help thank you.
CodePudding user response:
you have an extra ":" at the end of property name of your json, so try this json property names. This code was tested in Visual Studio and working properly
ResponseModel result = null;
if ( responseMessage.IsSuccessStatusCode)
{
var json = await responseMessage.Content.ReadAsStringAsync();
var jsonObject = JObject.Parse(json);
var data=jsonObject["data"];
if (data!=null) result = data.ToObject<ResponseModel>();
}
public class ResponseModel
{
[JsonProperty("totalcount:")]
public int totalcount { get; set; }
[JsonProperty("tpa:")]
public int tpa { get; set; }
[JsonProperty("tip:")]
public int tip { get; set; }
}
or you can fix an API
CodePudding user response:
In my model I added the colon ":" since the return value of the properties in the API has a ":" colon per property.
public class ResponseModel
{
[JsonProperty(PropertyName = "totalcount:")]
public int totalcount { get; set; }
[JsonProperty(PropertyName = "tpa:")]
public int tpa { get; set; }
[JsonProperty(PropertyName = "tip:")]
public int tip { get; set; }
}