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 use FormatterServices.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 use
FormatterServices.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.