首页 > 解决方案 > Dotnet Core - JSON 值无法转换为 Newtonsoft.Json.Linq.JToken

问题描述

A 有一个 Blazor wasm 应用程序,其定义如下:

{
    public int StaticTableId { get; set; }
    public JArray StaticData { get; set; }

    public static void RunFluent(ModelBuilder modelBuilder)
    {
        EntityTypeBuilder<StaticTable> entity = modelBuilder.Entity<StaticTable>();
        entity.HasKey(p => p.StaticTableId);
        entity.Property(e => e.StaticData).HasConversion(
            v => v.ToString(),
            v => JArray.Parse(string.IsNullOrEmpty(v) ? "[]" : v)
        );
    }
}

请注意,RunFluentDbContext.OnModelCreating

使用控制器中的以下函数直接调用 API 会产生正确的结果;JSON 对象的列表。

// GET: api/StaticTable/5
[HttpGet("{id}")]
public async Task<ActionResult<StaticTable>> StaticTable(int id)
{
    var staticTable = await _context.StaticTables.FindAsync(id);

    if (staticTable == null)
    {
        return NotFound();
    }

    return staticTable;
}

但是,尝试将此数据拉到前端会产生以下错误:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] 未处理的异常呈现组件:无法将 JSON 值转换为 Newtonsoft.Json.Linq.JToken。路径:$.projectAnalyses[0].jobInstances[4].resultsData.staticTable.staticData[0] | 行号:0 | BytePositionInLine:3263。`

SO 上的类似问题建议ConfigureServices()通过调用来更新AddNewtonsoftJson(),但这已经到位。

更新StaticTable.StaticData为 typeJToken也会给我一个错误:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] 未处理的异常呈现组件:集合类型“Newtonsoft.Json.Linq.JToken”是抽象的、接口或只读的,无法实例化和填充。

标签: c#.net-coreblazorblazor-webassembly

解决方案


推荐阅读