Alexandre
Alexandre

Reputation: 4602

Honoring JsonSerializer settings when creating a custom JsonConverter with Newtonsoft

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?

Upvotes: 3

Views: 522

Answers (1)

Maxime
Maxime

Reputation: 46

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();
    }
}

Upvotes: 3

Related Questions