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.
The deserialization process does not use the object's constructor - the object is instantiated without a constructor and initialized using the serialized instance data.
Constructors are not called when objects are deserialized. Therefore, any logic that executes during normal construction needs to be implemented as one of the serialization callbacks.
Jackson uses default (no argument) constructor to create object and then sets value using setters. so you only need @NoArgsConstructor and @Setter.
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.
A constructor is always invoked. I usually have two constructors. One for serialization (the default constructor) and one for all "regular" code:
[DataContract]
public class Component
{
// for JSON.NET
protected Component()
{
}
public Component(allMandatoryFieldsHere)
{
// I'm doing some magic here.
}
}
In that way I can also make sure that the dev specify all information which are required.
However, I do not really recommend that you use anything but DTO's when transfering information since it's otherwise possible to circumvent the encapsulation of your objects (anyone could initialize any field with any value). Well. If you use anything but anemic models.
Using FormatterServices.GetSafeUninitializedObject
is imho therefore an ugly workaround, since no one can tell that you create all objects in an unintialized way. Constructor initialization is there for a reason. It's better that the classes can tell that it's OK to not call the real constructor by providing a "serialization" constructor as I suggested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With