0

How to change the default JSON DateTime serialization/deserialization to a custom format using DataContractJsonSerializer for all DateTime properties in the object graph?

The Json.Net library deals with this but I can't use that in this project.

I tried IDataContractSurrogatebut I cannot access the value -> string conversion for DateTimes.

The model and expected JSON are:

[DataContract]
public class Client
{
    [DataMember(Name = "id")]
    public int Id {get; set; }
    [DataMember(Name = "name")]
    public string Name {get; set; }
    [DataMember(Name = "contacts")]
    public IList<Contact> Contacts {get; set; }
    [DataMember(Name = "created")]
    public DateTime Created {get; set; }
    [DataMember(Name = "changed")]
    public DateTime Changed {get; set; }
}

[DataContract]
public class Contact
{
    [DataMember(Name = "name")]
    public string Name {get; set; }
    [DataMember(Name = "created")]
    public DateTime Created {get; set; }
}

{
    "id": 123,
    "name": "Client Name",
    "contacts": [
        {
            "name": "Contact Name",
            "created": "2014-01-25 02:12:43"
        }
    ],
    "created": "2014-01-25 01:11:23"
    "changed": "2014-01-25 03:22:41"
}
João Angelo
  • 56,552
  • 12
  • 145
  • 147
Max Bündchen
  • 1,283
  • 17
  • 38

1 Answers1

8

I might be missing something, but try passing the desired date and time format in the settings when creating the serializer:

var serializer = new DataContractJsonSerializer(
    typeof(Client),
    new DataContractJsonSerializerSettings {
        DateTimeFormat = new DateTimeFormat("yyyy-MM-dd hh:mm:ss"),
    });
João Angelo
  • 56,552
  • 12
  • 145
  • 147