ASP.NET调用YesNo API反序列化JSON返回Null问题求助
问题:ASP.NET调用YesNo API反序列化JSON返回Null值
我是ASP.NET新手,尝试向YesNo API发送GET请求,但在将JSON响应反序列化并赋值给变量时得到Null值,恳请协助解决!
控制器代码
[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响应示例
{ "answer": "no", "forced": false, "image": "https://yesno.wtf/assets/no/20-56c4b19517aa69c8f7081939198341a4.gif" }
调试情况
data变量已正确获取到API返回的完整JSON内容YesNoData变量的所有属性值均为Null
解决方案
问题核心:YesNoModel的属性没有添加公共访问修饰符(public),Json.NET默认仅能序列化/反序列化公共属性,因此无法匹配JSON中的字段,导致属性值全部为Null。
1. 修正模型类
给YesNoModel的所有属性添加public修饰符:
public class YesNoModel { public string answer { get; set; } public bool forced { get; set; } public string image { get; set; } }
2. 可选优化建议
(1)使用异步/await替代.Result
避免阻塞线程,提升性能:
[Route("GetYesNo")] public async Task<HttpResponseMessage> GetYesNo() { Uri apiUrl = new Uri("https://yesno.wtf/api"); using (HttpClient client = new HttpClient()) { YesNoModel yesNoData = new YesNoModel(); var httpResponse = Request.CreateResponse(HttpStatusCode.OK); HttpResponseMessage response = await client.GetAsync(apiUrl); if (response.IsSuccessStatusCode) { string data = await response.Content.ReadAsStringAsync(); yesNoData = JsonConvert.DeserializeObject<YesNoModel>(data); } httpResponse.Content = new StringContent(JsonConvert.SerializeObject(yesNoData), Encoding.UTF8, "application/json"); return httpResponse; } }
(2)添加JsonProperty特性规范字段映射
如果后续使用C#标准的PascalCase命名(如Answer而非answer),可以通过JsonProperty特性明确对应JSON字段名:
public class YesNoModel { [JsonProperty("answer")] public string Answer { get; set; } [JsonProperty("forced")] public bool Forced { get; set; } [JsonProperty("image")] public string Image { get; set; } }
内容的提问来源于stack exchange,提问作者trickster625
相关产品推荐
相关产品推荐

