Custom Web Api Json Converter For A Single Property

23 בSeptember 2014

tags: , , ,
no comments

The web is well documented regarding usage of a custom Json Converter. Basically the idea is to inherit from JsonConvert, explore the current serialized type and use your own custom behavior when serializing.

1

The custom Json Convert can be used explicitly by calling Json.Convert or implicitly by registering in Application_Start.

Explicit:

2

Implicit:

3

The implicit registration will serialize every object that contains the specified type (DateTime? in our example) using the MyJsonDateTimeConverter Converter.

The explicit usage will only affect the current serialized value.

The other case

Both technics won’t work in the following case;

I need the converter to work only on a specified property, but I cannot use the explicit way since then I’ll have to change my action signature which returns IHttpActionResult<DateTime?>, since JsonConvert.SerializeObject returns a string, and will enforce me to return IHttpActionResult<string>.

On the other hand, I can’t use the implicit way since I don’t want to effect the entire application and the way it serializes DateTime? type. What I do want is to change the way a single specific property is been serialized.

Solution:

After writing my own JsonConverter as mentioned earlier, I added the JsonConverterAttribute which ” Instructs the Newtonsoft.Json.JsonSerializer to use the specified Newtonsoft.Json.JsonConverter”. Adding this sugar to a property in a class should do the trick.

4

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*