8

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.

akhansari
  • 954
  • 9
  • 13
  • 1
    You can't force to it to accept anything, but you can convert it to match it. – Aske B. Aug 30 '12 at 17:09
  • I'm no expert on this, but I think that it also has something to do with conversion to/from Epoch time. I've messed with similar before but since you have no code and I haven't worked with the two classes you're mentioning, I can't really help much further but I hope this helps you. – Aske B. Aug 30 '12 at 17:23
  • Thank you Aske. Now when working with System.Json I no longer use the default serializer but I convert the DateTime to "/Date(" + EpochDateTime + ")/" string. It solves my problem for now I think. – akhansari Aug 30 '12 at 17:52
  • Check out the solutions for this question similar to yours http://stackoverflow.com/questions/9266435/datacontractjsonserializer-deserializing-datetime-within-listobject – vendettamit Dec 26 '12 at 16:48
  • 2
    May [Json.NET](http://james.newtonking.com/projects/json-net.aspx) treats it differently. – S.M.Amin Sep 17 '13 at 21:16

1 Answers1

1

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);
    }

}
kb0
  • 522
  • 3
  • 8