3

I created a custom JsonConverter for a specific type.

public class FooNewtonsoftConverter : JsonConverter<Foo>{
    public override void WriteJson(JsonWriter writer, Foo value, JsonSerializer serializer)
    {
        writer.WriteStartObject();

        // Should it be serialized as "Id" or "id"?
        writer.WritePropertyName("id");
        writer.WriteValue(value.Id);

        writer.WriteEndObject();
    }
}

It is possible to customize the JsonSerializer to use a different naming strategy, such as CamelCasePropertyNamesContractResolver or changing the NamingStrategy to a CamelCaseNamingStrategy.

You can also decorate the property with a JsonProperty to change the name.

How can I resolve the right property names for the properties I'm serializing?

Alexandre
  • 4,382
  • 2
  • 23
  • 33
  • I think who has the final word is the receiving end (according to how they expect it), then the naming convention standards document of your company. This may be related: https://stackoverflow.com/questions/5543490/json-naming-convention – Oguz Ozgul Apr 03 '20 at 13:47

1 Answers1

3

If you look at the built-in KeyValuePairConverter you'll see they use

var resolver = serializer.ContractResolver as DefaultContractResolver;

writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyName) : KeyName);

In your scenario, it would look something like that:

public class FooNewtonsoftConverter : JsonConverter<Foo>{
    public override void WriteJson(JsonWriter writer, Foo value, JsonSerializer serializer)
    {
        writer.WriteStartObject();

        var resolver = serializer.ContractResolver as DefaultContractResolver;
        writer.WritePropertyName(resolver?.GetResolvedPropertyName("Id") ?? "Id");
        writer.WriteValue(value.Id);

        writer.WriteEndObject();
    }
}
Maxime
  • 46
  • 3