JSON 值无法转换为 Newtonsoft.Json.Linq.JToken。路径:$ | 行号:1 | 字节位置内联:8

Ati*_*hav 1 json.net

我有一个带有更新操作的 ASP.Net Core WebApi,如下所示:

   [HttpPut("{id}")]
    public async Task<IActionResult> Campaigns(long id, JObject jobject)
    {

    }
Run Code Online (Sandbox Code Playgroud)

当我从邮递员点击这个端点时的请求和响应如下:-

{
"Zone_Code": 1,
"State_Code": 24,
"City_Code": 25,
"Sales_Associate": null,
"Operation_Associate": null,
"Traveller": null,
"Target_Sector": 5,
"Campaign_DateTime": "2020-04-04T00:00:00",
"Format": 2,
"Campaign_Name": "Test",
"Data_Criteria": null,
"IsActive":"Y",
"Stage": "Initiation"
}


{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|58a198b0-4ac4ca0838cdebce.",
"errors": {
    "$": [
        "The JSON value could not be converted to Newtonsoft.Json.Linq.JToken. Path: $ | LineNumber: 1 | BytePositionInLine: 8."
    ]
}}
Run Code Online (Sandbox Code Playgroud)

Dar*_*oon 12

您的代码中有一个例外,因为您在 ASP.Net Core WebAPI - 中使用了默认的 json 序列化器/反序列化器System.Text.Json。您可以在文档中找到,System.Text.Json不支持这种反序列化。

您需要将默认的 json 序列化器/反序列化器切换为Newtonsoft.Json,请执行以下步骤:

  1. 安装Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet 包。
  2. ConfigureServices()添加呼叫AddNewtonsoftJson()
serviceCollection.AddControllers()
.AddNewtonsoftJson();
Run Code Online (Sandbox Code Playgroud)

有关更多信息,System.Text.Json您可以在Microsoft 博客中找到


Mar*_*dig 5

我相信根本问题是 .net core 3 使用 System.Text.Json。我相信您想使用 System.Text.Json.JsonElement。请参阅https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to