简体   繁体   中英

System.Text.Json.JsonException: The JSON value could not be converted

I'm using Ubuntu and dotnet 3.1, running vscode's c# extension.

I need to create a List from a JSON file, my controller will do some calculations with this model List that I will pass to it

I followed [these docs][1] examples

So, here is my code and the error I'm getting

First, I thought my error was because at model my attributes were char and C#, for what I saw, cannot interpret double-quotes for char, it should be single quotes. Before losing time removing it, I just changed my type declarations to strings and it's the same error.

Can someone help me?

ElevadorModel

using System.Collections.Generic;

namespace Bla
{
    public class ElevadorModel
    {
        public int andar { get; set; }
        public string elevador { get; set; }
        public string turno { get; set; }
    }

}

Program.cs:

class Program
    {
        static void Main(string[] args)
        {

            var path = "../input.json";

            string jsonString;
            
            ElevadorModel elevadoresModel = new ElevadorModel();

            jsonString = File.ReadAllText(path); //GetType().Name = String

            Console.WriteLine(jsonString); //WORKS           

            elevadoresModel = JsonSerializer.Deserialize<ElevadorModel>(jsonString);

        }

Your input json has an array as the base token, whereas you're expecting an object. You need to change your deserialization to an array of objects.

var elevadoresModels = JsonSerializer.Deserialize<List<ElevadorModel>>(jsonString);
elevadoresModel = elavoresModels.First();

您的输入 JSON 是一个模型数组,但是您正在尝试将其反序列化为单个模型。

var models = JsonSerializer.Deserialize<List<ElevadorModel>>(jsonString);

This is also a problem in Blazor-Client side. For those calling a single object
eg ClassName = await Http.GetFromJsonAsync<ClassName>($"api/ClassName/{id}");

This will fail to Deserialize. Using the same System.Text.Json it can be done by:

List<ClassName> ListName = await Http.GetFromJsonAsync<List<ClassName>>($"api/ClassName/{id}");

You can use an array or a list. For some reason System.Text.Json, does not give errors and it is successfully able Deserialize.

To access your object, knowing that it is a single object use:

ListName[0].Property

In your case the latter solution is fine but with the path as the input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM