JavaScriptSerializer将从IEnumerable派生的类型序列化为JavaScript数组。它对数组和列表很方便,但在某些情况下我需要序列化在派生类型中声明的属性(例如,键入IGrouping)。这里有一些示例代码:
var items = new[] { "aaabbb", "abcd", "bdsasd", "bsdqw" };
IGrouping<char, string> data = items.GroupBy(i => i[0]).First();
var serializer = new JavaScriptSerializer();
var serialized = serializer.Serialize(data);
// serialized == "[\"aaabbb\",\"abcd\"]"
// doesn't contain definition for IGrouping.Key property
这个问题有没有简单的解决方案?
答案 0 :(得分:3)
你可以试试这个:
var items = new[] { "aaabbb", "abcd", "bdsasd", "bsdqw" };
var data = (from x in items
group x by x[0] into g
select new
{
Key = g.Key,
Value = g
}).First();
var serializer = new JavaScriptSerializer();
var serialized = serializer.Serialize(data);
或者如果您愿意:
var items = new[] { "aaabbb", "abcd", "bdsasd", "bsdqw" };
var data = items.GroupBy(i => i[0])
.Select(x => new { Key = x.Key, Value = x })
.First();
var serializer = new JavaScriptSerializer();
var serialized = serializer.Serialize(data);
在这两种情况下,结果都是:
{"Key":"a","Value":["aaabbb","abcd"]}
答案 1 :(得分:2)
结帐JSON.NET。我已经在几个项目中使用它,它使JSON序列化和反序列化变得更加容易。它将使用单个方法调用序列化大多数对象,并且还允许您使用自定义属性对序列化进行更精细的控制。
以下是作者网站的样本:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);