1

I am trying to convert a particular IDictionary field of a particular class differently. I was thinking of doing this based on an attribute, but it looks like it wont work. Is it possible to somehow get the CustomAttribute associated with the type in CanConvert?

 [CustomAttribute] public IDictionary<string, string> AdditionalData { get; set; } // Custom converter for CustomAttribute public override bool CanConvert(Type objectType) { return System.Attribute.GetCustomAttributes(objectType).Any(v => v is CustomAttribute); } 

1 Answer 1

3

If you want to use an attribute to apply a converter to a specific property, just use a [JsonConverter] attribute. There's really no need to invent your own.

[JsonConverter(typeof(YourCustomConverterClass))] public IDictionary<string, string> AdditionalData { get; set; } 

Note that if you apply a [JsonConverter] attribute it is no longer necessary to pass an instance of that converter to the serializer. Also, the converter's CanConvert method will not be called for that property because Json.Net already knows you want to use the converter with it.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks Brian! But this approach does not work in nancy. I am using Nancy and it uses a preconfigured JsonSerializer and it only works with preconfigured set of Converters which is global. So If I have a custom converter defined for IDictionary<string, string> then all the IDictionary types in application will be converted using the custom converter.
JsonConverter is ignored only when making request from Postman but runs fine when making a request from application, not sure if it is because of header configuration in postman or sth else
You probably should have mentioned you are using Nancy in your question; this seems like an important detail, particularly if it has special behavior with respect to how converters work. Normally, in Json.Net, placing a [JsonConverter] attribute on a property causes it to be picked up by the serializer, regardless of any other converters that are configured in settings. If this is not happening then it sounds like Nancy must be using a contract resolver which removes this behavior for some reason. Unfortunately I am not familiar with Nancy at all, so I can't help you solve this.
I added the Nancy tag to your question. Maybe someone else familiar with the framework can help you.
@Silvan If your goal is to obfuscate certain properties for logging purposes, maybe you don't need a converter at all. See How to mask sensitive values in JSON for logging purposes. If you still want to apply a JsonConverter conditionally, you'll need to use a custom ContractResolver to do that. Here is an example that may help you: stackoverflow.com/a/63472122/10263
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.