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

StackOverflow https://stackoverflow.com/questions/17882193

سؤال

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)

هل كانت مفيدة؟

المحلول 2

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)

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top