5

I'm writing a client that consumes an API (of which I have no control over). Unfortunately the API's different endpoints are returning inconsistently named JSON fields. For example one endpoint is returning errorCode but another might return ErrorCode.

I'm using System.Text.Json in my .NET Core application for serialization. I would like to do something like the following:

public class MyErrorsResponse
{
    [JsonPropertyName("errorCode")]
    [JsonPropertyName("ErrorCode")]
    public string Code { get; set; }
}

Unfortunately this is not allowed at compile time and I get the error: CS0579 Duplicate 'JsonPropertyName' attribute.

Is there anyway round this problem? I tried the idea of a 2nd private setter like in: multiple JsonProperty Name assigned to single property. However, it would appear that System.Text.Json only serializes public fields and ignores private fields.

bytedev
  • 8,252
  • 4
  • 48
  • 56
  • 4
    If the only difference is in case you could set `JsonSerializerOptions.PropertyNameCaseInsensitive = true` as shown in [JsonSerializer.Deserialize fails](https://stackoverflow.com/q/60123376/3744182). – dbc Mar 01 '21 at 04:59
  • 1
    Thanks. Most are case insensitive problems, so this could help with a lot of them (though I'm suspicious how much this will effect performance). But I do have a couple where the string is slightly different. – bytedev Mar 01 '21 at 05:24
  • 1
    This link might help you https://stackoverflow.com/questions/43714050/multiple-jsonproperty-name-assigned-to-single-property – Arib Yousuf Mar 01 '21 at 06:04
  • There's nothing like that currently, and `System.Text.Json` [does not make its contract resolver public](https://stackoverflow.com/q/58926112/3744182). You could write a custom converter for `MyErrorsResponse` or add multiple properties. 1) How do you want your object to be re-serialized? 2) Are you using .NET Core 3.x or .NET 5? – dbc Mar 01 '21 at 14:01
  • 2
    Assuming you are working in .NET 5, your most least disruptive option may be to use `PropertyNameCaseInsensitive` to resolve the majority of the inconsistencies, and use surrogates properties to resolve the remainder. See https://dotnetfiddle.net/Ww3cOZ. The other option would be to roll your own custom converter for classes where this is an issue. – dbc Mar 02 '21 at 19:03
  • @dbc do you happen to have a sample with custom converter? – alhazen Aug 25 '21 at 10:34
  • 1
    @alhazen - there are many converter samples in the docs: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to. Or see e.g. [Properties of extended dictionary won't show in serialization](https://stackoverflow.com/a/59524410/3744182), [System.Text.Json - Deserialize nested object as string](https://stackoverflow.com/a/60402592/3744182) or [Custom JSON serializer for optional property with System.Text.Json](https://stackoverflow.com/a/63431434/3744182) for examples here. – dbc Aug 25 '21 at 15:22

0 Answers0