Search code examples
c#jsonjavascriptserializer

How do I make the JavaScriptSerializer automatically call a constructor/method/anything to initialize values after deserializing?


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!


Solution

  • 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 initialization

    Remarks

    You can register one or more custom converters with a JavaScriptSerializer instance by using the RegisterConverters method. When custom converters are registered, JavaScriptSerializer uses the converters both to serialize managed types and to deserialize JSON strings to managed types.

    And from JavaScriptConverter

    Remarks

    The JavaScriptConverter class enables you to implement serialization and deserialization processes for managed types that are not natively supported by the JavaScriptSerializer class. You can also use JavaScriptConverter when you need more control over the serialization and deserialization process.

    The only other way would be to manually call some initialization() method.