WCF JSON Deserialization Issues with Whitespace WCF JSON Deserialization Issues with Whitespace json json

WCF JSON Deserialization Issues with Whitespace


This is a known issue which was fixed in the 4.5 framework. Unfortunately you essentially need to strip the white spaces from the front of the object if you want to use polymorphism in the current framework version. One way to do that is to read / write the JSON using a reader / writer created by JsonReaderWriterFactory, as it will strip the white spaces (or any pretty printing) around the elements.

public class StackOverflow_8661714{    [DataContract(Name = "SuperClass", Namespace = "WhitespaceTest")]    [KnownType(typeof(SubClass))]    public class SuperClass    {        [DataMember]        public string Message { get; set; }    }    [DataContract(Name = "SubClass", Namespace = "WhitespaceTest")]    public class SubClass : SuperClass    {        [DataMember]        public string Extra { get; set; }    }    public static void Test()    {        string originalJson = "{    \"__type\":\"SubClass:WhitespaceTest\",    \"Message\":\"Message\",    \"Extra\":\"Extra\" }";        byte[] originalJsonBytes = Encoding.UTF8.GetBytes(originalJson);        MemoryStream writeStream = new MemoryStream();        XmlDictionaryWriter jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(writeStream, Encoding.UTF8, false);        XmlDictionaryReader jsonReader = JsonReaderWriterFactory.CreateJsonReader(originalJsonBytes, 0, originalJsonBytes.Length, XmlDictionaryReaderQuotas.Max);        jsonWriter.WriteNode(jsonReader, true);        jsonWriter.Flush();        Console.WriteLine(Encoding.UTF8.GetString(writeStream.ToArray()));        writeStream.Position = 0;        DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(SuperClass), new Type[] { typeof(SubClass) });        object o = dcjs.ReadObject(writeStream);        Console.WriteLine(o);    }}


Unfortunately, I have no good answer to this. We ran into the same issue and contacted Microsoft about it. They insisted that what they were doing was okay because of performance concerns, which is laughable considering how the entire pipeline works.

So our experience has been that whitespace in many places causes issues. Also, if you put the __type field anywhere but the first, you'll get the supertype.

My advice would be to look at other solutions to JSON. Unfortunately I'm not up on the alternatives or I'd suggest something.

Edit: As carlosfigueira points out, this has apparently been fixed in 4.5. I have not tried it there as of yet.