简体   繁体   English

ASP.NET 反序列化 JSON 返回 Null

[英]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.我是 ASP.NET 的新手,我正在尝试向 YesNo API 发出 GET 请求。

However, when trying to deserialize the JSON response and assign the value to to a variable I get null values.但是,当尝试反序列化 JSON 响应并将值分配给变量时,我得到 null 值。

Any assistance would be appreciated!任何援助将不胜感激!

Controller code: Controller 代码:

    [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: Postman 响应示例:

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

The value of the data variable during debugging: data var value调试时data变量的值: data var value

The value of the YesNoData variable during debugging: YesNoData var value调试时YesNoData变量的值: 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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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