2

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

2 Answers 2

3

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; }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Make your properties public

public class YesNoModel
{ 
   public  string Answer { get; set; }
   public  bool Forced { get; set; }
   public  string Image { 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.