JC Grubbs JC Grubbs - 9 months ago 46
JSON Question

How do I serialize a C# anonymous type to a JSON string?

I'm attempting to use the following code to serialize an anonymous type to JSON:

var serializer = new DataContractJsonSerializer(thing.GetType());
var ms = new MemoryStream();
serializer.WriteObject(ms, thing);
var json = Encoding.Default.GetString(ms.ToArray());

However, I get the following exception when this is executed:

cannot be serialized. Consider marking
it with the DataContractAttribute
attribute, and marking all of its
members you want serialized with the
DataMemberAttribute attribute. See
the Microsoft .NET Framework
documentation for other supported

I can't apply attributes to an anonymous type (as far as I know). Is there another way to do this serialization or am I missing something?


Try the JavaScriptSerializer instead of the DataContractJsonSerializer

JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(your_anon_object);