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

标签 c# json anonymous-types datacontractjsonserializer json-serialization

我正在尝试使用以下代码将匿名类型序列化为 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);

关于c# - 如何将 C# 匿名类型序列化为 JSON 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/331976/

相关文章:

c# - GET ALL Skype Friends using skype APIs With C# 获取所有 Skype 好友

android - 天气 api 的 JSON 日期解析

ios - Swift 2 使用 swiftyJSON 从在线 URL 解析 JSON

java - Java 中的匿名类型类似于 C#

c# - 如何有条件地更改 <img src =""> 值? | Razor CSHTML

c# - IdentityServer启用引用 token

javascript - 传递给initialPreview属性的<img>标签数组

.net - 匿名类型缺少成员问题的动态 View - MVC3

C# SQL To Linq - 具有多个变量的Where 子句比较 (var1+var2) !=(var1+var2)

c# - 在 Windows 窗体中为控件使用通用事件处理程序!