9

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."
    ]
}}
3
  • 1
    Why you use JObject like a parameter of the action?you can use a simple object Commented Mar 24, 2020 at 13:30
  • My handler code uses reflection to set properties' values Commented Mar 25, 2020 at 5:44
  • i don't see the handler in your question, i tried a simple test, with JObject gives me the same error, and with a simple object i'm calling the Action. Commented Mar 25, 2020 at 7:43

2 Answers 2

35

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

Sign up to request clarification or add additional context in comments.

2 Comments

Does this still work? When I run command VS isn't able to find the package to install it...
Try command dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson --version 6.0.9, but it is for .net 6.0. If you use the previous version, install another version.
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.