I was implementing a unit test to invoke a PATCH endpoint, using "System.Text.Json" to serialize the data and send it as content. I was always getting BAD REQUEST, until I found out that the serializer encapsulates the whole patch document inside the "Operations" list and adds a property called "ContractResolver".
My work around was to use Newtonsoft.Json serializer, that, at least by default, doesn't add the extra property and it work properly since the API accepts the JsonDocumentPatch.
Anyone now why "System.Text.Json" serializer works that way and not simply convert to JSON just like newtonsoft does? or if it is possible to config something to prevent that. I don't want to use both serializers inside the project.. Oh, and I'm using .NET6 with latests nuget packages (until the date of this post)
I have been documentation and nothing comes up regarding that.
Thanks for your time in reading this even if you don't have an answer. Cheers..
Some sample code for the serialization:
var patchOperations = new JsonPatchDocument<BodyModel>();
patchOperations.Replace(m => m.IntValue, 123);
patchOperations.Remove(m => m.StringValue);
var systemSerializer = JsonSerializer.Serialize(patchOperations);
var newtonSerializer = JsonConvert.SerializeObject(patchOperations);
The results are:
systemSerializer
{
"Operations":[
{
"value":123,
"OperationType":2,
"path":"/IntValue",
"op":"replace",
"from":null
},
{
"value":null,
"OperationType":1,
"path":"/StringValue",
"op":"remove",
"from":null
}
],
"ContractResolver":{
}
}
newtonSerializer
[
{
"value":123,
"path":"/IntValue",
"op":"replace"
},
{
"path":"/StringValue",
"op":"remove"
}
]