views:

153

answers:

2

Can silverlight 3 serialize annonymous objects?

A: 

Do you mean anonymous as in var? That can't be serialized by anything.

Dave Swersky
I mean anonymous as in:<pre><code>new { MyProperty = "Something", MyLocation = "Somewhere" }</code></pre>and you can serialize it using JavaScriptSerializer in normal .Net applications, but it doesnt appear to be available in silverlight. Too bad. For what its worth there is no reason anonymous types cant be serialized, it's deserializing them thats the problem.
Mr Bell
+1  A: 

No silverlight 3 can't serialize an anonymous type. The only JSON serializer that Silverlight has is the DataContractJsonSerializer. However this requires types to be decorated with the DataContractAttribute and members to be decorated with DataMemberAttribute which will not be true of anonymous types.

However if your purpose is to query some existing data and generate a JSON string output then you might consider using classes found in the System.Json namespace. Here is an example:-

/// <summary>
/// Helper methods to reduce code needed in constructing JSON items
/// </summary>
public static class JsonHelper
{  
 public static KeyValuePair<string, JsonValue> CreateProperty(string name, string value)
 {
  return new KeyValuePair<string, JsonValue>(name, new JsonPrimitive(value));
 }
 public static KeyValuePair<string, JsonValue> CreateProperty(string name, int value)
 {
  return new KeyValuePair<string, JsonValue>(name, new JsonPrimitive(value));
 }
 // Replicate above for each constructor of JsonPrimitive
 public static KeyValuePair<string, JsonValue> CreateProperty(string name, JsonValue value)
 {
  return new KeyValuePair<string, JsonValue>(name, value);
 }
}

The above is simply a helper static class so that the code in the following LINQ query doesn't get to hairy. The DataProvider just generates some test data which in this case is a list of objects that have a Name property. This noddy example simply generates a list of objects that have a name property and a count property that contains the count of characters in the name property.

var list = from item in DataProvider.DataItems()
  select (JsonValue)(new JsonObject(
   JsonHelper.CreateProperty("name", item.Name),
   JsonHelper.CreateProperty("count", item.Name.Length)
   ));

var result = (new JsonArray(list)).ToString();
AnthonyWJones
Oh well, I thought this might be the case. Too bad. I hope they bring back JavaScriptSerializer in Silverlight, soon.
Mr Bell