When using ISerializable with DataContractSerializer, how do I stop the serializer from outputting type information?
Do you need the ISerializable
here? What was the regular DataContractSerializer
not giving you? If you switch back to this, it should work fine.
Basically, by implementing custom serialization, the data is no longer contract based - so it has to include this extra information to guarantee that it is able to understand it later.
So: is there a reason to implement ISerializable
in this case?
If you want full control over serialization to xml, you can use XmlSerializer
public class Test{ [XmlIgnore] public Nullable<int> NullableNumber = 7; [XmlElement("NullableNumber")] public int NullableNumberValue { get { return NullableNumber.Value; } set { NullableNumber = value; } } public bool ShouldSerializeNullableNumberValue() { return NullableNumber.HasValue; } [XmlElement] public int Number = 5;}
sample serialization code:
static void Main(string[] args){ XmlSerializer serializer = new XmlSerializer(typeof(Test)); serializer.Serialize(Console.Out, new Test());}
results:
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Number>5</Number> <NullableNumber>7</NullableNumber></Test>
Starting in .Net Framework 4.5 (and .Net Core 1.0), this is possible using the DataContractJsonSerializerSettings
class:
DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings{ EmitTypeInformation = EmitTypeInformation.Never};var dcs = new DataContractSerializer(typeof(Test), settings);
The EmitTypeInformation
settings tells the serializer not to output the (annoying?) __type
parameter during serialization.
There are a range of other useful settings available. Here is the docs page for DataContractJsonSerializerSettings
.