如何反序列化类,而不调用构造函数? [英] How to deserialize class without calling a constructor?
问题描述
我在我的WCF数据服务使用Json.NET
下面是我的课(简体):
[DataContract]
公共类组件
{
公共组件()
{
//我在做什么一些魔术在这里。
}
}
如何反序列化类的没有的调用使用构造 JsonConvert.DeserializeObject
?
很抱歉,如果不清楚,请随时提问。
-
您可以创建从
CustomCreationConverter继承的类
,并使用FormatterServices.GetSafeUninitializedObject
以创建您的
对象。它会跳过调用构造函数。
更多关于CustomCreationConverter的这里。
-
配售
[JSONObject的(MemberSerialization.Fields) ]
一类将Json.NET使用
FormatterServices.GetSafeUninitializedObject
默认情况下(虽然
场模式也将连载公共/私人领域,而不是
公共属性,您可能不希望)。 -
动你不希望默认的外部运行逻辑构造函数。
I'm using Json.NET in my WCF data service.
Here's my class (simplified):
[DataContract]
public class Component
{
public Component()
{
// I'm doing some magic here.
}
}
How can I deserialize that class without invoking a constructor using JsonConvert.DeserializeObject
?
Sorry if not clear, feel free to ask questions.
You could create a class that inherits from
CustomCreationConverter
and useFormatterServices.GetSafeUninitializedObject
to create your object. It skips calling the constructor.More about CustomCreationConverter here.
Placing
[JsonObject(MemberSerialization.Fields)]
on a class will make Json.NET useFormatterServices.GetSafeUninitializedObject
by default (although Fields mode will also serialize public/private fields rather than public properties which you may not want).Move the logic you don't want run outside of the default constructor.
这篇关于如何反序列化类,而不调用构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!