0

What do first 3 bytes written by JsonSerializer on the begging of stream mean and why does DataContractJsonSerializer have a problem with them?

Sample:

Foo foo = new Foo();

using (MemoryStream stream = new MemoryStream())
{
    //serialize using JsonSerializer
    using (var streamWriter = new StreamWriter(stream, Encoding.UTF8, 4096, true))
    using (var jsonWriter = new JsonTextWriter(streamWriter))
    {
        JsonSerializer jsonSerializer = JsonSerializer.Create();
        jsonSerializer.Serialize(jsonWriter, foo, typeof(Foo));
    }

    // reset position
    stream.Seek(0, SeekOrigin.Begin);

    // deserialize using DataContractJsonSerializer
    using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(stream, Encoding.UTF8, XmlDictionaryReaderQuotas.Max, null))
    {
        DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(Foo));
        foo = (Foo)dataContractJsonSerializer.ReadObject(jsonReader);
    }
}

Deserialization ends up with exception: Additional information: There was an error deserializing the object of type Sandbox.Program+Foo. Encountered unexpected character 'ï'.

dbc
  • 104,963
  • 20
  • 228
  • 340
eCorke
  • 858
  • 1
  • 10
  • 24
  • 1
    Don't even try. DataContractJsonSerializer is *ancient*, obsolete and created before there was any form of standardization for Json. For example, when DataContractJsonSerializer was created there was no JSon date format, so it used a Unix timestamp (ie number of ms since 1970-01-01). The ISO 8601 was adopted years later – Panagiotis Kanavos Mar 30 '16 at 11:12
  • 2
    PS the first 3 bytes are the Unicode BOM. These have nothing to do with JSon. These are artifacts of the stream writers. – Panagiotis Kanavos Mar 30 '16 at 11:14
  • About `DataContractJsonSerializer` - I'm not, server side does and I've forgot about BOM, little bit embarrassing. – eCorke Mar 30 '16 at 11:25
  • You *could* run into trouble though, if the server tried to send dates. BTW even whitespace handling wasn't standardized until a few years ago, with naive implementations choking eg with newlines inside strings – Panagiotis Kanavos Mar 30 '16 at 11:26
  • Does doing `var streamWriter = new StreamWriter(stream, new System.Text.UTF8Encoding(false), 4096, true)` as @PanagiotisKanavos suggested solve the problem? – dbc Mar 30 '16 at 16:48

0 Answers0