I’m playing around with JSON and the .Net JavascriptSerializer, it’s all looking good and fun so far, here’s my code:
JavaScriptSerializer serializer = new JavaScriptSerializer();
myObject = serializer.Deserialize<MyObject>(myJsonString);
Now I wanna take it one step further by performing some initialization, like setting some values inside MyObject after it has been created using deserialization. I’ve tried adding a parameterless constructor to MyObject class, public MyObject(), and doing the setting of values there, but it doesn’t seem to be called automatically.
How do I call some initialization method / constructor after the deserialization? Please note that I only wanna use JavascriptSerializer (that’s what I’m learning for now), don’t wanna use datacontractserializer or other json libraries or external dlls. Thanks for reading!
From
JavaScriptSerializer.Deserialize<T>, I don’t see how a constructor gets called.There is however the method
JavaScriptSerializer.RegisterConverters, which allows custom converters, where you can do your own initializationAnd from
JavaScriptConverterThe only other way would be to manually call some
initialization()method.