Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json DateTime serialization is different in DataContractJsonSerializer and System.Json

How can I force DataContractJsonSerializer to accept System.Json DateTime serialization format (ISO 8601) ?

The problem is that System.Json output "2012-03-01T16:24:55.000" format but DataContractJsonSerializer need "/Date(1329161615596+0200)/" format.

I have this error : There was an error deserializing the object of type xyz. DateTime content '2012-03-01T16:24:55.000' does not start with '/Date(' and end with ')/' as required for JSON.

like image 969
akhansari Avatar asked Aug 30 '12 17:08

akhansari


1 Answers

You can write an adapter class which pre-processes your serialized data during deserialization, and plumbs all other functions through to the sealed DataContractJsonSerializer class.

public class DataContractSystemJsonSerializer : XmlObjectSerializer
{

    protected DataContractJsonSerializer innerSerializer;


    public DataContractSystemJsonSerializer(Type t)
    {
        this.innerSerializer = new DataContractJsonSerializer (t);
    }
    ...

    public override Object ReadObject(Stream stream)
    {
        Object obj = null;
        MemoryStream out = new MemoryStream();
        Byte[] buf = new Byte[64];
        stream.Read(buf,0,64);

        int i = 0;
        while(stream.Read(buf,i,1))
        {
          convertDatesInBuffer(&buf, &i);              

          out.write(buf, i, 1);

          i = (i+1)%64;
        }

        return innerSerializer.ReadObject(out);
    }

}
like image 61
kb0 Avatar answered Sep 28 '22 09:09

kb0