How to deserialize class without calling a constructor?

后端 未结 4 857
长发绾君心
长发绾君心 2021-01-01 16:38

I\'m using Json.NET in my WCF data service.

Here\'s my class (simplified):

[DataContract]
public class Component
{
    public Component()
    {
              


        
4条回答
  •  时光取名叫无心
    2021-01-01 16:51

    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.

提交回复
热议问题