Igor Shastin Igor Shastin - 2 months ago 9x
C# Question

How to deserialize class without calling a constructor?

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

Here's my class (simplified):

public class Component
public Component()
// I'm doing some magic here.

How can I deserialize that class without invoking a constructor using

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.