我的 Web 应用程序中有一个 API 请求,但每次我将响应结果转换为反序列化对象时,它都会为我的模型提供空值。
这是我的代码:
var contents = await responseMessage.Content.ReadAsStringAsync();
var statusInfo = responseMessage.StatusCode.ToString();
if (statusInfo == "OK")
{
var jsonresult = JObject.Parse(contents);
var respond = jsonresult["data"].ToString();
var result = JsonConvert.DeserializeObject<ResponseModel>(respond);
}
内容值为
"{\"data\":{\"totalcount:\":8113,\"tpa:\":6107,\"tip:\":5705},\"message\":\"success\"}"
响应值为
"{ \r\n"totalcount:\": 8113,\r\n \"tpa:\": 6107,\r\n \"tip:\": 5705\r\n}"
我的模型是
public class ResponseModel
{
[JsonProperty(PropertyName = "totalcount")]
public int totalcount { get; set; }
[JsonProperty(PropertyName = "tpa")]
public int tpa { get; set; }
[JsonProperty(PropertyName = "tip")]
public int tip { get; set; }
}
请帮忙谢谢。
你有一个额外的“:”在你的 json 属性名称的末尾,所以试试这个 json 属性名称。此代码已在 Visual Studio 中测试并正常工作
ResponseModel result = null;
if ( responseMessage.IsSuccessStatusCode)
{
var json = await responseMessage.Content.ReadAsStringAsync();
var jsonObject = JObject.Parse(json);
var data=jsonObject["data"];
if (data!=null) result = data.ToObject<ResponseModel>();
}
public class ResponseModel
{
[JsonProperty("totalcount:")]
public int totalcount { get; set; }
[JsonProperty("tpa:")]
public int tpa { get; set; }
[JsonProperty("tip:")]
public int tip { get; set; }
}
或者你可以修复一个 API
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句