Search code examples
c#arraysjson.netasp.net-core-mvc

ASP.NET Core MVC works only with Json-Files with 1 object in it


I am not sure how to explain my problem corectly but I will try my best.
My MVC accepts Json-Files like this one

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

but not Json-Files with more than one "Object" in it

[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false
  },
  {
    "userId": 1,
    "id": 3,
    "title": "fugiat veniam minus",
    "completed": false
  }
]

This is my MVC and this way it works but when I replace the URL (https://jsonplaceholder.typicode.com/todos) to have a Json-File with more than 1 "Object" in it my Webpage gives me an Error.

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ToDo.Models;
using System.Net;

namespace ToDo.Controllers
{
    public class ToDoData : Controller
    {
        public ActionResult ToDoModel()
        {
            var webClient = new WebClient();
            webClient.Headers.Add(HttpRequestHeader.Cookie, "cookievalue");
            var json = webClient.DownloadString(@"https://jsonplaceholder.typicode.com/todos/1");
            ToDoStructure ToDoData = JsonConvert.DeserializeObject<ToDoStructure>(json);

            return View(ToDoData);
        }
    }
}

Can someone help with this problem?
The Error:

JsonSerializationException: Cannot deserialize the current JSON array 
(e.g. [1,2,3]) into type 'ToDo.Models.ToDoStructure' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize 
correctly. To fix this error either change the JSON to a JSON object 
(e.g. {"name":"value"}) or change the deserialized type to an array or 
a type that implements a collection interface (e.g. ICollection, IList) 
like List<T> that can be deserialized from a JSON array. 
JsonArrayAttribute can also be added to the type to force it to 
deserialize from a JSON array. Path '', line 1, position 1.

The Razor-Page where I want to display the data as a Table

@model ToDo.Models.ToDoStructure
@{
    ViewBag.Title = "ToDoModel";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>ToDoModel</h2>
@{ 
<table>
    <tr>
        <th>userId</th>
        <th>id</th>
        <th>title</th>
        <th>completed</th>
    </tr>
    <tr>
        <th>@Model.userId</th>
        <th>@Model.id</th>
        <th>@Model.title</th>
        <th>@Model.completed</th>
    </tr>
</table>
}

Solution

  • If you want only two (generic) JSON models, you need use:

    var _todoData = JsonConvert.DeserializeObject<List<>>(json)
    

    In this case, _todoData will be a list.

    Then, in your view, you need use _todoData, and in your HTML, tr needs a foreach, since you will now be working with a list! (This is what the error is saying.)