简体   繁体   中英

ASP.NET Deserialize JSON Returns Null

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

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

Make your properties public

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM