1

I have this setup

  • Asp Core 3.1 API
  • Shared Lib with MyClass that is sent between API and client
  • Client App with Com classes

On the MyClass that is sent between them I have a field ComField that references a com class, this is only used on the client app and should not be (de)serialized, therefore I have it marked with [JsonIgnore]

class MyClass{
  [JsonIgnore]
  public ComThingy ComField {
    get{// code here that throws the error when deserilaized on the API}
    set{// code here}
  }
}

When I write the API to accept the class like this, I get an error when the class is deserialized. The debugger throws the error while deserializing the MyClass, before it enters the method:

[HttpPost]
public async Task<ActionResult<MyClassReply>> Post([FromBody] MyClass myclass){
    // code here 
}

The API throws an exception that accessing the getter on MyClass throws an error (because that Com stuff isn't on the API).

If I deserialize manually it works fine, but then my swagger doesn't generate the whole API correctly.

[HttpPost]
public async Task<ActionResult<MyClassReply>> Post(){

    // this works fine
    var rdr = new StreamReader(Request.Body);
    var mcj = await rdr.ReadToEndAsync();           
    var myclass = Newtonsoft.Json.JsonConvert.DeserializeObject<MyClass>(mcj);

    // code here 
}

So my question is: how come the ASP API builtin deserialization ignores the JsonIgnore attribute and still tries to deal with that property (throwing an error), and why does deserializing manually work as expected (ie ignore that property)? The default pipeline still uses NewtonSoft rght?

And how do I make the default deserialization work correctly?

gjvdkamp
  • 9,929
  • 3
  • 38
  • 46

1 Answers1

2

Starting from ASP.NET Core 3.0, the default JSON serializer is System.Text.Json, and not Newtonsoft.Json. You need to call .AddNewtonsoftJson() in your Startup.cs to use it (see for example this answer).

Your issue might simply be that you're not using the proper JsonIgnore attribute. Both serializers have the same named attribute:

Maybe your using statement are importing the Newtonsoft.Json one instead of the System.Text.Json one?

Métoule
  • 13,062
  • 2
  • 56
  • 84