I've been working win MVC Web API and encountered an annoying problem. It does not, by default serialise anonymous data members.
1 2 |
[DataMember] public object text = new { status = "generated", div = "<table><tr><th>Code</th><th>Interpreation</th></tr></table>"}; |
When you try to serialise this kind of data you get this beautiful exception:
1 |
Type '<>f__AnonymousType3`2[System.String,System.String]' cannot be serialised. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want to be serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types. |
Converting anonymous type to a string also caused exception. But there is also JavaScriptSerializer
:
1 2 3 |
var x = new { blah = "afd" }; JavaScriptSerializer serializer = new JavaScriptSerializer(); var serialized = serializer.Serialize(x); |
Now using getter
, I tried combining the two:
1 2 3 |
private object text = new { status = "generated", div = "<table><tr><th>Code</th><th>Interpreation</th></tr></table>"}; [DataMember] public object Text = {get {return text;};set;} |
That seems to have done the trick.