Error:
‘Cannot deserialize the current JSON array (e.g. [1,2,3]) into type ‘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();
}
}
I have a custom model CustomActionResult
and it add “is-success” and “message” to the end of data I tried CustomActionResult<PostViewModel>
but it didn’t work either.
My data format is like this:
{
"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; }
}
CustomActionResult:
public class CustomActionResult
{
public bool IsSuccess { get; set; }
public string Message { get; set; }
}
public class CustomActionResult<T> : CustomActionResult
{
public T Data { get; set; }
}
4
The error you are facing is deserialization of JSON array into a single object.
I have updated the code below.
[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();
}