如何序列化一个C#匿名类型以JSON字符串? [英] How do I serialize a C# anonymous type to a JSON string?

查看:469
本文介绍了如何序列化一个C#匿名类型以JSON字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用下面的code序列化一个匿名类型的JSON:

I'm attempting to use the following code to serialize an anonymous type to JSON:

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

不过,我得到以下异常这是执行时:

However, I get the following exception when this is executed:

类型
  '<> f__AnonymousType1`3 [System.Int32,System.Int32,System.Object的[]'
  不能被序列化。考虑标记
  它与DataContractAttribute
  属性,和标记所有的其
  会员想要序列化的
  DataMemberAttribute属性。看到
  Microsoft .NET框架
  支持其他文件
  类型。

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.

我不能申请属性一个匿名类型(据我所知)。是否有另一种方式来做到这一点的序列化还是我失去了一些东西?

I can't apply attributes to an anonymous type (as far as I know). Is there another way to do this serialization or am I missing something?

推荐答案

尝试的JavaScriptSerializer,而不是DataContractJsonSerializer

Try the JavaScriptSerializer instead of the DataContractJsonSerializer

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

这篇关于如何序列化一个C#匿名类型以JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆