0

We need to write a custom JsonConverter for DateTime and DateTime? in order to respect the date format specified with the DisplayFormat attribute.

[if anybody knows of an existing converter doing exactly this -> we would like to know of it :-)]

We derived our converter from JsonConverter, however, there seems to be no way to access any attributes as we do not have access to the property being converted - only to its type and value.

Is there any other way we overlooked? How to access attributes from within a JsonConverter?

D.R.
  • 20,268
  • 21
  • 102
  • 205
  • Will all of your dates have the same display format, or does it vary? – Brian Rogers Sep 18 '13 at 20:20
  • Varies, some will show the date only, some are going to show date and time. Otherwise we would have replaced the default serialization behavior. – D.R. Sep 18 '13 at 20:50

2 Answers2

1

From what I can see, there does not seem to be a way to access, from within a converter, the context (parent object) for the object being converted. Another answer (now deleted) claimed that you could by way of the Context property on the JsonSerializer, but this returns a StreamingContext which does not contain information about the parent object (its inner Context property is always null in my testing).

Perhaps a possible solution for your situation is to use a variation of the idea in this answer. In other words, create custom derivatives of the IsoDateTimeConverter, one for each different date format that you require. I'm guessing there will only be a small number of these needed. Then, decorate your DateTime properties with the [JsonConverter] attribute, specifying which custom date converter to use for each property based on the date format needed.

Community
  • 1
  • 1
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
0

You can put the parent object in the StreamingContext.Context which is a place holder for extra information in OnSerializing callback of the parent object. I suggest defining this context as a dictionary of string and object and with predefined keys. In the converter then you can get the stored additional information from Serializer.Context.

Arash
  • 147
  • 2
  • 14