0

I'm interfacing with an API which uses snake_case as convention names. I would like to map them to fields which are named with CamelCase. Previously, I've used Newtonsoft.Json's NamingStrategy. A System.Text.Json equivalent seems to be PropertyNamingPolicy.

I've created a global JsonSerializerOptions object and set the PropertyNamingPolicy as follows:

public static readonly `JsonSerializerOptions` JsonSettings = new JsonSerializerOptions()
{
    Converters =
    {
        new GatewayMessageJsonConverter(),
        new HeartbeatMessageJsonConverter(),
        new OpcodeJsonConverter(),
        new InstantJsonConverter()
    },
    IgnoreNullValues = true,
    PropertyNamingPolicy = new JsonSnakeCaseNamingPolicy(),
    DictionaryKeyPolicy = new JsonSnakeCaseNamingPolicy()
};

Which I use while deserializing by passing it as an argument:

JsonSerializer.Deserialize<GatewayRestResponse>(responseString.Result, JsonSettings)

This however does not work. Debugging seems to indicate that the ConvertName function in the JsonSnakeCaseNamingPolicy never even gets called.

Is my configuration wrong, or does System.Text.Json not support this?

Sander K.
  • 41
  • 1
  • 4
  • 1
    *I would like to map them to fields...* **`System.Text.Json` does not support fields.** If you are really using fields not properties, that's your problem. See [How to use class fields with System.Text.Json.JsonSerializer?](https://stackoverflow.com/q/58139759/3744182). Otherwise, please [edit] your question and include a [mcve] so we can help you. – dbc Jun 13 '20 at 00:23
  • 1
    It seems like that was the issue. Thank you, I did not know there was a difference. – Sander K. Jun 13 '20 at 00:43
  • It's reasonable to be surprised, other serializers besides `System.Text.Json` can serialize public fields. Not sure why microsoft made that choice. – dbc Jun 13 '20 at 00:45

0 Answers0