【问题标题】:The JSON value could not be converted to Newtonsoft.Json.Linq.JToken. Path: $ | LineNumber: 1 | BytePositionInLine: 8JSON 值无法转换为 Newtonsoft.Json.Linq.JToken。路径:$ |行号:1 |字节位置行内:8
【发布时间】:2020-07-04 23:47:05
【问题描述】:

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

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

    }

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

{
"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."
    ]
}}

【问题讨论】:

  • 为什么你使用JObject作为动作的参数?你可以使用一个简单的对象
  • 我的处理程序代码使用反射来设置属性值
  • 我在您的问题中没有看到处理程序,我尝试了一个简单的测试,JObject 给了我同样的错误,并且使用 simple object 我是调用 Action.

标签: json.net


【解决方案1】:

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

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

  1. 安装Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet 包。
  2. ConfigureServices() 中添加对AddNewtonsoftJson() 的呼叫
serviceCollection.AddControllers()
.AddNewtonsoftJson();

有关System.Text.Json的更多信息,您可以在Microsoft blog找到

【讨论】:

  • 这对我很有帮助。谢谢。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 1970-01-01
    • 2022-08-12
    • 1970-01-01
    相关资源
    最近更新 更多