[英]System.Text.Json.JsonException: The JSON value could not be converted
I'm using Ubuntu and dotnet 3.1, running vscode's c# extension.我正在使用 Ubuntu 和 dotnet 3.1,运行 vscode 的 c# 扩展。
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我需要从 JSON 文件创建一个列表,我的控制器将使用我将传递给它的模型列表进行一些计算
I followed [these docs][1] examples我遵循 [这些文档] [1] 示例
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.首先,我认为我的错误是因为在模型中我的属性是 char 和 C#,就我所见,不能解释 char 的双引号,它应该是单引号。 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:程序.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.您的输入 json 有一个数组作为基本标记,而您需要一个对象。 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.这也是 Blazor-Client 端的一个问题。 For those calling a single object
对于那些调用单个对象的人
eg ClassName = await Http.GetFromJsonAsync<ClassName>($"api/ClassName/{id}");
例如
ClassName = await Http.GetFromJsonAsync<ClassName>($"api/ClassName/{id}");
This will fail to Deserialize.这将无法反序列化。 Using the same System.Text.Json it can be done by:
使用相同的 System.Text.Json 可以通过以下方式完成:
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.
出于某种原因,System.Text.Json 不会出错,并且可以成功反序列化。
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.在您的情况下,后一种解决方案很好,但以路径作为输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.