如何从DataContract中排除类型信息? [英] How can I exclude the Type information from the DataContract?

查看:122
本文介绍了如何从DataContract中排除类型信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从序列化中排除__type键和值:

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"}

我正在使用System.Runtime.Serialization.Json.DataContractJsonSerializer.

我不得不将Types标记为KnownTypes,这似乎是将__type引入序列化的原因.

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?

如果不使用带有DataContract的类的KnownType属性,它将起作用,但是如果没有该类,我会在该类成员的Types上获得各种异常.

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.

推荐答案

我可以肯定地说,除非在多态场景中不对类型进行序列化,否则无法做到这一点.

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

一种可能的解决方案是创建某种不会调用多态性的包装器操作,然后通过该操作而不是通过poly方法返回对象.

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.

JSON序列化程序确实有一个名为alwaysEmitTypeInformation的标志,但是您必须打开它才能始终发出__type.现在,有一种方法可以将其关闭,主要是为了避免意外的用户错误.

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.

这篇关于如何从DataContract中排除类型信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆