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.

Community
  • 1
  • 1
Fred Fickleberry III
  • 2,439
  • 4
  • 34
  • 50
  • if you mean without applying the attribute you want to serialize the object?? use the `Newtonsoft.json` install this package from `NuGet` – Deepak Sharma Nov 10 '15 at 09:10

1 Answers1

4

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));
}
toadflakz
  • 7,764
  • 1
  • 27
  • 40
  • To set the converter globally, see [How to tell Json.Net globally to apply the StringEnumConverter to all enums](http://stackoverflow.com/questions/7427909/how-to-tell-json-net-globally-to-apply-the-stringenumconverter-to-all-enums). – dbc Nov 10 '15 at 09:52