Control JSON Serialization format of a custom type in .NET
- by mrjoltcola
I have a PhoneNumber class that stores a normalized string, and I've defined implicit operators for string <- Phone to simplify treatment of the PhoneNumber as a string. I've also overridden the ToString() method to always return the cleaned version of the number (no hyphens or parentheses or spaces). In any MVC.NET code where I explicitly display the number, I can explicitly call phone.Format().
The problem here is serializing an entity that has a PhoneNumber to JSON; JavaScriptSerializer serializes it as [object Object].
I want to serialize it as a string in (555)555-5555 format.
I've looked at writing a custom JavaScriptConverter, but JavaScriptConverter.Serialize() method returns a dictionary of name-value pairs. I don't want PhoneNumber to be treated as an object with fields, I want to simply serialize it as a string.