0

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.

2
  • Also you're using .ToString() too often. 😉 Commented Apr 8, 2022 at 6:03
  • @Oliver I already show the contents result. Thank you Commented Apr 8, 2022 at 6:05

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

The result variable gives 0 for all properties of model
@YasSmitch This code was tested in Visual Studio and working properly. You have to fix all properties of model. BTW "{\"data\" doesn' t have an extra ":", this is why it is working
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.