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