Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing anonymous types in Silverlight with json.net

I'm having some problems serializing an anonymous type only on the Silverlight platform. I have code on .net 4.0 and .netcf that works fine.

This line right here

Newtonsoft.Json.JsonConvert.SerializeObject(new { Something = "yup" });

throws an aptly named guy, JsonSerializationException:

Error getting value from 'Something' on '<>f__AnonymousType0`1[System.String]'.

I tried 4.0r1 and 4.0r2 - Am I doing something wrong or am I taking crazy pills?

like image 586
user140550 Avatar asked Jul 12 '11 08:07

user140550


2 Answers

The problem is that anonymous types are defined as internal classes by the compiler. JSON.NET relies on reflection to work, and in Silverlight reflection across assembly borders work only for public types (when used by partially trusted assemblies such as this one).

I think DataContractJsonSerializer as mentioned in the previous answer is the way to go in this case, since it's part of the framework and should have extra privileges.

Another thing to try is use dictionaries or ExpandoObject's instead of anonymous types, but YMMV.

like image 188
Stefan Dragnev Avatar answered Sep 30 '22 18:09

Stefan Dragnev


Answer is simple;) Add [assembly: InternalsVisibleTo("Newtonsoft.Json")] to AssemblyInfo.cs and voila... I have exactly the same problem and this attribute solved my serialization/deserialization problem.

AssemblyInfo.cs

[assembly: InternalsVisibleTo("Newtonsoft.Json")] 
like image 28
zielu1 Avatar answered Sep 30 '22 18:09

zielu1