如何反序列化类,而不调用构造函数? [英] How to deserialize class without calling a constructor?

查看:1258
本文介绍了如何反序列化类,而不调用构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的WCF数据服务使用Json.NET



下面是我的课(简体):

  [DataContract] 
公共类组件
{
公共组件()
{
//我在做什么一些魔术在这里。
}
}

如何反序列化类的没有的调用使用构造 JsonConvert.DeserializeObject



很抱歉,如果不清楚,请随时提问。


解决方案

  1. 您可以创建从 CustomCreationConverter继承的类
    ,并使用 FormatterServices.GetSafeUninitializedObject 以创建您的
    对象。它会跳过调用构造函数。



    更多关于CustomCreationConverter的这里


  2. 配售
    [JSONObject的(MemberSerialization.Fields) ] 一类将Json.NET使用
    FormatterServices.GetSafeUninitializedObject 默认情况下(虽然
    场模式也将连载公共/私人领域,而不是
    公共属性,您可能不希望)。


  3. 动你不希望默认的外部运行逻辑构造函数。



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.

解决方案

  1. You could create a class that inherits from CustomCreationConverter and use FormatterServices.GetSafeUninitializedObject to create your object. It skips calling the constructor.

    More about CustomCreationConverter here.

  2. Placing [JsonObject(MemberSerialization.Fields)] on a class will make Json.NET use FormatterServices.GetSafeUninitializedObject by default (although Fields mode will also serialize public/private fields rather than public properties which you may not want).

  3. Move the logic you don't want run outside of the default constructor.

这篇关于如何反序列化类,而不调用构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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