Windows Universal App 8.1。 DataContractJsonSerializer始终为Windows Phone App 8.1发出派生类的类型信息。它对Windows Store App 8.1的行为正确。
测试代码和结果如下。除了编辑json post序列化之外,还有任何解决方法吗?
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
namespace TestEmitTypeInformation
{
[DataContract]
public class DataContractBase
{
[DataMember]
public string BaseString { get; set; }
}
[DataContract]
public class DataContractDerived : DataContractBase
{
[DataMember]
public string DerivedString { get; set; }
}
public class DataContractTest
{
public static void SerializeTestAll()
{
var test = new DataContractTest();
test.SerializeTest(System.Runtime.Serialization.EmitTypeInformation.Always);
test.SerializeTest(System.Runtime.Serialization.EmitTypeInformation.AsNeeded);
test.SerializeTest(System.Runtime.Serialization.EmitTypeInformation.Never);
}
public void SerializeTest(EmitTypeInformation emitTypeInfo)
{
var testObject = new DataContractDerived() { BaseString="Base", DerivedString="Derived" };
using (MemoryStream memStream = new MemoryStream())
{
var serializationSettings =
new DataContractJsonSerializerSettings()
{
EmitTypeInformation = emitTypeInfo,
KnownTypes = new Type[] { typeof(DataContractDerived) }
};
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(DataContractBase), serializationSettings);
ser.WriteObject(memStream, testObject);
memStream.Position = 0;
string jsonContent = new StreamReader(memStream).ReadToEnd();
Debug.WriteLine("Result: EmitTypeInformation {0}\n{1}", emitTypeInfo, jsonContent);
}
}
}
}
调用DataContractTest.SerializeTestAll()的结果是: - Windows 8.1
Result: EmitTypeInformation Always
{"__type":"DataContractDerived:#TestEmitTypeInformation","BaseString":"Base","DerivedString":"Derived"}
Result: EmitTypeInformation AsNeeded
{"__type":"DataContractDerived:#TestEmitTypeInformation","BaseString":"Base","DerivedString":"Derived"}
Result: EmitTypeInformation Never
{"BaseString":"Base","DerivedString":"Derived"}
Windows Phone 8.1
Result: EmitTypeInformation Always
{"__type":"DataContractDerived:#TestEmitTypeInformation","BaseString":"Base","DerivedString":"Derived"}
Result: EmitTypeInformation AsNeeded
{"__type":"DataContractDerived:#TestEmitTypeInformation","BaseString":"Base","DerivedString":"Derived"}
Result: EmitTypeInformation Never
{"__type":"DataContractDerived:#TestEmitTypeInformation","BaseString":"Base","DerivedString":"Derived"}