Can silverlight 3 serialize annonymous objects?
Do you mean anonymous as in var
? That can't be serialized by anything.
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();