Control JSON Serialization format of a custom type in .NET
Posted
by mrjoltcola
on Stack Overflow
See other posts from Stack Overflow
or by mrjoltcola
Published on 2010-04-08T01:15:31Z
Indexed on
2010/04/08
1:23 UTC
Read the original article
Hit count: 595
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.
© Stack Overflow or respective owner