2009-11-05 63 views

回答

1

没有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属性的对象的列表。这诺迪例如简单地生成有name财产,包含name属性的字符个数一个count属性的对象的列表。

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(); 
+0

哦,我想这可能是这样的。太糟糕了。我希望他们能很快带回Silverlight中的JavaScriptSerializer。 – 2009-11-05 15:06:37

-1

你的意思是匿名在var?这不能被任何东西序列化。

+0

我的意思是匿名的,如:

 new { MyProperty = "Something", MyLocation = "Somewhere" } 
,您可以在正常的.Net应用程序中使用JavaScriptSerializer序列化,但它不似乎是在Silverlight提供。太糟糕了。对于它的价值是什么没有理由匿名类型不能序列化,它是反序列化他们多数民众赞成在这个问题。 – 2009-11-05 15:00:51