views:

208

answers:

1

Does anyone know of decent examples of custom JavaScriptConverter classes? The MSDN's only example is of one converting a ListItemCollection. What about custom classes? What if the custom class has a property of another custom class? Do we need two converters? Any references would be greatly appreciated.

Thanks!

A: 

You should only need one converter. The example basically outlines how to use the JavaScript converter for any custom class. It doesn't need to be a class that is part of the framework.

It will also work for any properties of a custom class that are themselves a custom class.

JSON views objects as collections of key/value pairs, so the documentation example shows how you should take any properties of your object and put them into Dictionaries (a type of Key/Value pair object). If you need a nested custom type, you can just nest Key/Value pairs inside of your main Key/Value pair collection.

Also, unless you have very specific needs (built-in serialization either won't work, or doesn't output what you want), you should just use the JavaScriptSerializer class.

JavaScriptSerializer serializer = new JavaScriptSerializer();
MyCustomObject obj = new MyCustomObject();
string json = serializer.Serialize(obj);

MyCustomObject object2 = serializer.Deserialize<MyCustomObject>(json);

That should do what you want in 95% of cases.

Dan Herbert