c# - 如何将 C# 匿名类型序列化为 JSON 字符串?

我正在尝试使用以下代码将匿名类型序列化为 JSON:

var serializer = new DataContractJsonSerializer(thing.GetType());
var ms = new MemoryStream();
serializer.WriteObject(ms, thing);
var json = Encoding.Default.GetString(ms.ToArray()); 

但是,执行此操作时出现以下异常:

Type '<>f__AnonymousType1`3[System.Int32,System.Int32,System.Object[]]' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. See the Microsoft .NET Framework documentation for other supported types.

我无法将属性应用于匿名类型(据我所知)。还有其他方法可以进行此序列化还是我遗漏了什么?

最佳答案

尝试 JavaScriptSerializer 而不是 DataContractJsonSerializer

JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(your_anon_object);

https://stackoverflow.com/questions/331976/

相关文章:

ios - 如何使用 NSJSONSerialization

python - 如何在 Python 中检查字符串是否是有效的 JSON?

javascript - 在 JavaScript 中将 JSON 字符串解析为特定的对象原型(pr

python - 将类实例序列化为 JSON

jquery - TypeError : $. ajax(...) 不是函数?

python - 存储 Python 字典

php - json_encode() 转义正斜杠

python - 如何将网页中的 JSON 转换为 Python 脚本

javascript - JSON 省略了 Infinity 和 NaN; ECMAScript 中

java - HttpServletRequest 获取 JSON POST 数据