Atish Jadhav
Atish Jadhav

Reputation: 71

The JSON value could not be converted to Newtonsoft.Json.Linq.JToken. Path: $ | LineNumber: 1 | BytePositionInLine: 8

I have a ASP.Net Core WebApi with a update Action as follows:

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

    }

The request and response when I hit this endpoint from postman are below:-

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

Upvotes: 7

Views: 22398

Answers (2)

DarkSideMoon
DarkSideMoon

Reputation: 1063

You have an exception in your code, because you use default json serializer/deserializer in ASP.Net Core WebAPI - System.Text.Json. You can find in documentations, that System.Text.Json doesn't support such deserialization.

You need to switch your default json serializer/deserializer to Newtonsoft.Json, do the following steps:

  1. Install the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package.
  2. In ConfigureServices() add a call to AddNewtonsoftJson()
serviceCollection.AddControllers()
.AddNewtonsoftJson();

For more information about System.Text.Json you can find in Microsoft blog

Upvotes: 34

Mark Nadig
Mark Nadig

Reputation: 5136

I believe the root issue is .net core 3 uses System.Text.Json. I believe you want to use System.Text.Json.JsonElement. See https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to

Upvotes: 5

Related Questions