I am trying to get data from this Json Rest API and display in View using ASP.NET MVC. I followed this tutorial.
I am getting an error saying 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[diversity.Models.Species]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'userId', line 2, position 12.'
I am aware of other related questions such as this. However, this suggests to replace <List<Species>>
with <Species>
. If I did this, it causes error regarding @model IEnumerable<diversity.Models.Species>
in the view.
I think the response from the api is a not a list but a single object. Then how can I properly implement this? And If I had to get a list in the future, how should I change the code?
Here is my code.
SpeciesController.cs
using diversity.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LinqToWiki.Download;
using LinqToWiki.Generated;
using LinqToWiki;
using System.Text;
using RestSharp;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using Newtonsoft.Json;
namespace diversity.Controllers
{
public class SpeciesController : Controller
{
public async System.Threading.Tasks.Task<ActionResult> SpeciesDetails(){
HttpClient client = new HttpClient();
List<Species> datalist = new List<Species>();
try
{
HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
datalist = JsonConvert.DeserializeObject<List<Species>>(responseBody);
}
catch (HttpRequestException e)
{
System.Diagnostics.Debug.WriteLine("\nException Caught!");
System.Diagnostics.Debug.WriteLine("Message :{0} ", e.Message);
}
client.Dispose();
return View(datalist);
}
}
}
Species.cs (Model)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace diversity.Models
{
public class Species
{
public int UserId { get; set; }
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
}
SpeciesDetails.cshtml
@model IEnumerable<diversity.Models.Species>
@{
ViewBag.Title = "SpeciesDetails";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>SpeciesDetails</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.UserId)
</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Body)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserId)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Body)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>