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>
}
CodePudding user response:
Try to receive it into string before deserializing it to the expected list object. follow the below format and revert back:
string responseBody = webClient.DownloadString(urladdress); JavaScriptSerializer json_serializer = new JavaScriptSerializer();//or json serializer
List items = json_serializer.Deserialize<List>(responseBody); foreach (var item in items) { //loop through if need be
}
CodePudding user response:
if you want only 2. Json model (generic)
you need use ;
var _todoData = JsonConvert.DeserializeObject<List<>>(json)
_todoData (will be a list)
and in view, you need use _todoData,
and in html "tr" need like foreach. Because now you will work with LIST! (your error say this)