learnerplates
learnerplates

Reputation: 4387

How can I exclude the Type information from the DataContract?

I want to exclude the __type Key and Value from my serialization:

{"__type":"Entity:#Runtime.DataBus","Children":[],"Fields":[{"Key":"field1","Value":"10"},{"Key":"fieldString1","Value":"field1 init"},{"Key":"fieldString2","Value":"field2 init"}],"Name":"Entity1"}

I'm using the System.Runtime.Serialization.Json.DataContractJsonSerializer.

I've had to mark the Types as KnownTypes and it appears to be this that's pulling the __type into the serialization.

I do not want it in my object, how can this be done?

Without using the KnownType attribute on the class with the DataContract it would work but without it in this class I get all sorts of exceptions on this classes member's Types.

Upvotes: 4

Views: 1500

Answers (2)

Chielus
Chielus

Reputation: 632

In newer versions you can use the following code

DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
settings.EmitTypeInformation = System.Runtime.Serialization.EmitTypeInformation.Never;

Upvotes: 4

krisragh MSFT
krisragh MSFT

Reputation: 1918

I can say definitively that there is no way to do this, unless you don't serialize the type in polymorphic scenarios.

One possible solution is create some type of wrapper operation that won't invoke polymorphism, and return the object via that operation instead of via the poly method.

The JSON serializer does have a flag called alwaysEmitTypeInformation, but it's something you turn ON to always emit __type. There is now way to turn it off, mainly to avoid unintentional user errors.

Upvotes: 2

Related Questions