【发布时间】:2009-11-05 02:13:42
【问题描述】:
Silverlight 3 可以序列化匿名对象吗?
【问题讨论】:
标签: c# silverlight json serialization
Silverlight 3 可以序列化匿名对象吗?
【问题讨论】:
标签: c# silverlight json serialization
没有 silverlight 3 不能序列化匿名类型。 Silverlight 拥有的唯一 JSON 序列化程序是 DataContractJsonSerializer。但是,这需要使用 DataContractAttribute 修饰的类型和使用 DataMemberAttribute 修饰的成员,这不适用于匿名类型。
但是,如果您的目的是查询一些现有数据并生成 JSON 字符串输出,那么您可以考虑使用在 System.Json 命名空间中找到的类。这是一个例子:-
/// <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);
}
}
以上只是一个辅助静态类,因此以下 LINQ 查询中的代码不会变得繁琐。 DataProvider 只是生成一些测试数据,在这种情况下是具有Name 属性的对象列表。这个 noddy 示例仅生成一个对象列表,这些对象具有 name 属性和 count 属性,其中包含 name 属性中的字符数。
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();
【讨论】:
您的意思是像var 那样匿名吗?这不能被任何东西序列化。
【讨论】:
new { MyProperty = "Something", MyLocation = "Somewhere" } 你可以使用 JavaScriptSerializer 在正常的 .Net 应用程序,但它似乎在 silverlight 中不可用。太糟糕了。就其价值而言,没有理由不能序列化匿名类型,而是将它们反序列化,这就是问题所在。