Home > other >  ASP.NET Deserialize JSON Returns Null
ASP.NET Deserialize JSON Returns Null

Time:09-07

I'm new to ASP.NET and I'm trying to make a GET request to the YesNo API.

However, when trying to deserialize the JSON response and assign the value to to a variable I get null values.

Any assistance would be appreciated!

Controller code:

    [RoutePrefix("api/YesNo")]
    public class YesNoController : ApiController
    {

        [Route("GetYesNo")]
        public HttpResponseMessage GetYesNo()
        {
            Uri loginUrl = new Uri("https://yesno.wtf/api");
            HttpClient client = new HttpClient();
            client.BaseAddress = loginUrl;

            YesNoModel YesNoData = new YesNoModel();
            var httpResponse = Request.CreateResponse(HttpStatusCode.OK);

            HttpResponseMessage response = client.GetAsync(client.BaseAddress).Result;
            if (response.IsSuccessStatusCode)
            {
                string data = response.Content.ReadAsStringAsync().Result;
                YesNoData = JsonConvert.DeserializeObject<YesNoModel>(data);
            }

            httpResponse.Content = new StringContent(JsonConvert.SerializeObject(YesNoData), Encoding.UTF8, "application/json");
            return httpResponse;
        }
    }
    class YesNoModel
    { 
        string answer { get; set; }
        bool forced { get; set; }
        string image { get; set; }
    }

Postman response example:

{
    "answer": "no",
    "forced": false,
    "image": "https://yesno.wtf/assets/no/20-56c4b19517aa69c8f7081939198341a4.gif"
}

The value of the data variable during debugging: data var value

The value of the YesNoData variable during debugging: YesNoData var value

CodePudding user response:

You need to specify your properties as public for them to be set in the deserialization.

class YesNoModel
{
    public string answer { get; set; }
    
    public bool forced { get; set; }
    
    public string image { get; set; }
}

CodePudding user response:

Make your properties public

public class YesNoModel
{ 
   public  string Answer { get; set; }
   public  bool Forced { get; set; }
   public  string Image { get; set; }
}
  • Related