Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize class without calling a constructor?

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.

like image 262
Igor Shastin Avatar asked Dec 19 '12 08:12

Igor Shastin


People also ask

Does DeSerialization call constructor?

The deserialization process does not use the object's constructor - the object is instantiated without a constructor and initialized using the serialized instance data.

Does DeSerialization call constructor C#?

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.

Does Jackson need a default constructor?

Jackson uses default (no argument) constructor to create object and then sets value using setters. so you only need @NoArgsConstructor and @Setter.

How do you deserialize an object?

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.


1 Answers

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.

like image 100
jgauffin Avatar answered Sep 25 '22 22:09

jgauffin