我需要將KnownType添加到下面的代碼中,以便序列化成功。當我這樣做,將生成的JSON如下:如何告訴DataContractJsonSerializer不包含「__type」屬性
JSON form of Adult with 1 child: {"age":42,"name":"John","children":[{"__type":"
Child:#TestJson","age":4,"name":"Jane","fingers":10}]}
我怎麼有它不包括「__type」:「孩子:#TestJson」?我們在一些查詢中返回了數百個這些元素,並且額外的文本會加起來。
全碼:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace TestJson
{
class Program
{
static void Main(string[] args)
{
Adult parent = new Adult {name = "John", age = 42};
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Adult));
ser.WriteObject(stream1, parent);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
Console.Write("JSON form of Adult with no children: ");
Console.WriteLine(sr.ReadToEnd());
Child child = new Child { name = "Jane", age = 4, fingers=10 };
stream1 = new MemoryStream();
ser = new DataContractJsonSerializer(typeof(Child));
ser.WriteObject(stream1, child);
stream1.Position = 0;
sr = new StreamReader(stream1);
Console.Write("JSON form of Child with no parent: ");
Console.WriteLine(sr.ReadToEnd());
// now connect the two
parent.children.Add(child);
stream1 = new MemoryStream();
ser = new DataContractJsonSerializer(typeof(Adult));
ser.WriteObject(stream1, parent);
stream1.Position = 0;
sr = new StreamReader(stream1);
Console.Write("JSON form of Adult with 1 child: ");
Console.WriteLine(sr.ReadToEnd());
}
}
[DataContract]
[KnownType(typeof(Adult))]
[KnownType(typeof(Child))]
class Person
{
[DataMember]
internal string name;
[DataMember]
internal int age;
}
[DataContract]
class Adult : Person
{
[DataMember]
internal List<Person> children = new List<Person>();
}
[DataContract]
class Child : Person
{
[DataMember]
internal int fingers;
}
}
這是我使用[JSON.Net](http://json.net) –
@MikeChristensen的一個重要原因之一:這真的不是一個原因,因爲'DataContractJsonSerializer'支持這一點以及... –
@DanielHilgarth - 是的,我認爲有一些方法可以控制這一點。我遇到了很多問題,我用默認的.NET序列化程序切換到第三方庫。 –