views:

64

answers:

2

I'd like to override the Serialize methods of the ASP.NET JavaScriptSerializer class. Nothing too fancy, I just want to do some additional post processing to the serialized string returned from .NET.

Unfortunately, none of the methods on this class are declared virtual and the class itself does not derive from an interface or abstract class (seems like a strange oversight given how many of the core .NET Framework classes are designed for extensibility).

Based on some reading I've done on the subject, it appears that I have a couple of options to choose from.

  • Create an extension method. I'm not a huge fan of this option, since it involves creating a new method (compiler won't allow using the same name/signature twice) that class consumers would need to be aware of.

  • Derive a new class from JavaScriptSerializer that has the exact same signature. Since JavaScriptSerializer has no virtual methods, I would use the "new" keyword in each method/property declaration in order to perform method hiding. I think this option is considered a decorator pattern?

  • Create a new interface called IJavaScriptSerializer that would have the same signature as JavaScriptSerializer. Remove all references in my code to JavaScriptSerializer and replace with references to the newly created interface.

I'd love to hear about additional approaches and the pros/cons of each approach.

Thanks for taking the time to read.

A: 

Go to http://json.org and d/l one of the several classes that have source code, for JSON serialization.

Then, put in your post-processing, compile and use in your project.

Ideally, at this point I would create an extension method so I can just do this:

List<MyObject> s = fillObject();
return s.ToJSON();
James Black
+2  A: 

You're misunderstanding the Decorator Pattern, which refers to an object that inherits a class and wraps another instance of that class. (This is very common for streams). In your case, it's inapplicable.

I would recommend that you make your own replacement (or wrapper, whichever you need) for the JavaScriptSerializer class, without trying to have an identical API. If you need to be able to swap implementations, I would make an interface or base class with the core methods, and have two concrete implementations of it, one wrapping the original and one adding your post-processing.

In general, when designing classes, you should design to meet your needs, not to copy the .Net Framework's built-in classes.

SLaks
This is my 400th answer!
SLaks