-
-
Save Encosia/6cfcdfdf2a117fa5e81b to your computer and use it in GitHub Desktop.
Make JavaScriptSerializer serialize ExpandoObject less like a sociopath.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
dynamic foo = new ExpandoObject(); | |
foo.name = "Conery"; | |
foo.company = "TekPub"; | |
foo.today = DateTime.Now; | |
var jss = new JavaScriptSerializer(); | |
jss.RegisterConverters(new JavaScriptConverter[] { new ExpandoObjectConverter() }); | |
Console.Write(jss.Serialize(foo)); | |
} | |
public class ExpandoObjectConverter : JavaScriptConverter | |
{ | |
public override IEnumerable<Type> SupportedTypes | |
{ | |
get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(ExpandoObject) })); } | |
} | |
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) | |
{ | |
ExpandoObject expando = (ExpandoObject)obj; | |
if (expando != null) | |
{ | |
// Create the representation. | |
Dictionary<string, object> result = new Dictionary<string, object>(); | |
foreach (KeyValuePair<string, object> item in expando) | |
{ | |
if (item.Value.GetType() == typeof(DateTime)) | |
result.Add(item.Key, ((DateTime)item.Value).ToShortDateString()); | |
else | |
result.Add(item.Key, item.Value.ToString()); | |
} | |
return result; | |
} | |
return new Dictionary<string, object>(); | |
} | |
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) | |
{ | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code is based on the example here on MSDN: http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptconverter.aspx