Matt
Matt

Reputation: 7254

Why is no constructor needed of the object, deserialized from a json string, using ServiceStack Json Serializer

I wonder why no constructor is necessary to deserialize a json string into a .Net/C# class object instance. I was surprised that the constructor is not invoked at all and removed it and the deserializer still created an object instance from the json string. Is this normal?

(I use the json serializer of ServiceStack)

Upvotes: 0

Views: 1531

Answers (2)

Fresa
Fresa

Reputation: 51

Germanns answer is not entirely true. It is possible to instantiate an object that has no default constructor without executing any constructor.

This is done with FormatterServices.GetUninitializedObject.

ServiceStack is using this method if it cannot find a default constructor, hence it can deserialize objects that have no default constructor.

Upvotes: 5

Germann Arlington
Germann Arlington

Reputation: 3353

Default (no parameters) constructor is created by the compiler if no constructors are specified. The compiler does that when and only when NO constructors exist. If you create ANY constructor in your class this compiler behaviour will no longer apply. (Try creating a constructor with at least one parameter to see what will happen)

Deserialization will involve two steps - create empty object using default (no parameters) constructor and than set all values. If you class does NOT have default (no parameters) constructor - either created by yourself explicitly or by the compiler - deserialization will fail.

Deserialization never uses parametrised constructors as it is impossible for it to guess the correct constructor to use. Example: deserialization can not distinguish between Constructor(String parameter1) and Constructor(String parameter2)

Upvotes: 2

Related Questions