EProgrammerNotFound
EProgrammerNotFound

Reputation: 2461

How Can I setup the Json.Net serializer to behave in a custom way?

When I serialize, all my dates will be as local times, in order to mantain the backward compatibility with legacy applications that read/write to the same database or perform server to server integration. But I want to produce UTC (ISO Format) string for web api my consumers, since they can be anywhere in my country. As I live in Brazil and this country has more than 1 timezone, I do have to deal with this locale mess.

When I deserialize, I want to convert a utc formatted string to local format, due to the backwards compatibilities.

Brazil (Brazilia Time) is at -03:00 offset, then:

When the web api consumer inputs: "...T18:00:00.000Z", on the web api side the DateTime time would need to become "15:00:00" in the local format.

When the web api outputs the very same "15:00:00" DateTime, the serializer should translate that time back to "...T18:00:00.000Z" in the utc format.

If possible, I would like an application-wide solution, IOW, I don't want to decorate every class or property with a custom JsonConverter

Can you advise me on that?

Upvotes: 1

Views: 779

Answers (1)

EProgrammerNotFound
EProgrammerNotFound

Reputation: 2461

What you described is the behavior of DateTimeZoneHandling.Local, at least in the 7.0.1 version, which is the newest version at the time this question was answered.

There is actually a minor difference: When the DateTime is serialized, the JSonConverter will produce the time in the offset format [15:00-03:00] instead of UTF format [18:00Z]. This is as expected, I believe (at least make sense to me), since the format in the SerializerSettings is DateTimeZoneHandling.Local, if it were DateTimeZoneHandling.Utc it would produce 18:00Z, as expected.

When the DateTime is deserialized, a value in UTC format such as "2015-01-01T18:00:00.000Z", will correctly become the same as new DateTime(2015, 1, 1, 15, 0, 0, DateTimeKind.Local).

To configure the JsonConvert add the following code in the Register() method of the WebApiConfig:

using Newtonsoft.Json;
...
public static void Register(HttpConfiguration config)
{
    var settings = config.Formatters.JSonFormatter.SerializerSettings;
    settings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
    settings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
}

Disclaimer: The tests results are from a -03:00 offset. (Brazilia Time)

Upvotes: 3

Related Questions