gpt4 book ai didi

asp.net - JSON:序列化从 IEnumerable 派生的类型

转载 作者:行者123 更新时间:2023-12-04 19:23:49 26 4
gpt4 key购买 nike

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

这个问题有什么简单的解决方案吗?

最佳答案

你可以试试这个:

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"]}

关于asp.net - JSON:序列化从 IEnumerable 派生的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1449142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com