错误:
'无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型'Mvc_Web_Application.Models.PostViewModel
public class BlogController : Controller
{
Uri baseAddress = new Uri("https://localhost:7181/api");
private readonly HttpClient _client;
public BlogController()
{
_client = new HttpClient();
_client.BaseAddress = baseAddress;
}
[HttpGet]
public IActionResult Index()
{
try
{
CustomActionResult < PostViewModel > posts = new CustomActionResult<PostViewModel>();
HttpResponseMessage response = _client.GetAsync(_client.BaseAddress + "/Blog/GetBlogs").Result;
if (response.IsSuccessStatusCode)
{
string data = response.Content.ReadAsStringAsync().Result;
posts = JsonConvert.DeserializeObject <CustomActionResult<PostViewModel>>(data);
return View(posts);
}
}
catch
{
throw new NotImplementedException();
}
return View();
}
}
我有一个自定义模型
CustomActionResult
,它在我尝试过的数据末尾添加了“is-success”和“消息”CustomActionResult<PostViewModel>
,但它也不起作用。
我的数据格式是这样的:
{
"data":
[
{
"title": "test1",
"body": "body",
"author": null,
"id": 1,
"createdDate": "0001-01-01T00:00:00",
"updatedDate": "0001-01-01T00:00:00"
},
{
"title": "test1",
"body": "body1",
"author": null,
"id": 2,
"createdDate": "0001-01-01T00:00:00",
"updatedDate": "0001-01-01T00:00:00"
}
],
"isSuccess": true,
"message": null
}
PostViewModel:
public class CustomActionResult
{
public bool IsSuccess { get; set; }
public string Message { get; set; }
}
public class CustomActionResult<T> : CustomActionResult
{
public T Data { get; set; }
}
自定义操作结果:
public class CustomActionResult
{
public bool IsSuccess { get; set; }
public string Message { get; set; }
}
public class CustomActionResult<T> : CustomActionResult
{
public T Data { get; set; }
}
您面临的错误是将 JSON 数组反序列化为单个对象。
我更新了下面的代码。
[HttpGet]
public IActionResult Index()
{
try
{
HttpResponseMessage response = _client.GetAsync(_client.BaseAddress + "/Blog/GetBlogs").Result;
if (response.IsSuccessStatusCode)
{
string data = response.Content.ReadAsStringAsync().Result;
CustomActionResult<List<PostViewModel>> posts = JsonConvert.DeserializeObject<CustomActionResult<List<PostViewModel>>>(data);
return View(posts);
}
}
catch
{
throw new NotImplementedException();
}
return View();
}