2

I have a custom JsonConverter for DateTimeOffset properties in my ViewModels. I have 100+ ViewModels.

public class ItemViewModel { public string Name { get; set; } [JsonConverter(typeof(CustomDateTimeOffsetConverter))] public DateTimeOffset DateCreated { get; set; } } 

How can I apply this attribute to all DateTimeOffset properties, without adding it to all my ViewModels?

I thought I had the solution when I read this answer, but when I apply it, the CustomResolver only fires on the parent object itself, and not the DateTimeOffset property, or any property.

public class CustomResolver : DefaultContractResolver { protected override JsonObjectContract CreateObjectContract(Type objectType) { JsonObjectContract contract = base.CreateObjectContract(objectType); if (objectType == typeof(DateTimeOffset)) { contract.Converter = new CustomDateTimeOffsetConverter(); } return contract; } } 

So to recap, I have everything else working. If I add the [JsonConverter(typeof(CustomDateTimeOffsetConverter))] attribute manually, then my application works like a charm. I am only asking how to add the attribute automatically, instead of manually.

1
  • if you mean without applying the attribute you want to serialize the object?? use the Newtonsoft.json install this package from NuGet Commented Nov 10, 2015 at 9:10

1 Answer 1

5

You need to add the converter to the JsonSerializerSettings.Converters passed to the serializer.

Your JsonSerializerSettings will look as follows:

var settings = new JsonSerializerSettings() { Converters = { new CustomDateTimeOffsetConverter() } }; 

Your custom converter should also advertise it can convert the DateTimeOffset type with the following override of the JsonConverter method:

public override bool CanConvert(Type objectType) { return (objectType == typeof(DateTimeOffset)); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.