将JSON反序列化为匿名对象 [英] Deserialize JSON to anonymous object

查看:449
本文介绍了将JSON反序列化为匿名对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我已经使用这样的代码成功地将匿名对象序列化为JSON ...

In C#, I am have successfully serialized an anonymous object into JSON by use of code like this...

var obj = new { Amount = 108, Message = "Hello" };
JavaScriptSerializer serializer = new JavaScriptSerializer();
String output = serializer.Serialize(obj);

但是,我以后想要做的是将JSON字符串反序列化为一个匿名对象.像这样...

However, what I would like to be able to do later is to deserialize the JSON string back into an anonymous object. Something like this...

var obj2 = serializer.Deserialize(output, object);

但是serializer.Deserialize()方法需要第二个参数,该参数是将反序列化到的对象的类型.

But the serializer.Deserialize() method requires a second parameter that is the type of object it will deserialize to.

我尝试过了...

var obj2 = serializer.Deserialize(output, obj.GetType());

但这会产生错误:

没有为'<> f__AnonymousType0`2 [[System.Int32,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089],[System.String,mscorlib,Version = 4.0]类型定义无参数构造函数.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]'.

No parameterless constructor defined for type of '<>f__AnonymousType0`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.

我不确定这个错误是什么意思.

I'm not sure what this error means.

推荐答案

JSON .Net 是一个功能强大的库,可以在.Net中使用JSON

JSON.Net is a powerful library to work with JSON in .Net

有一种方法您可以点击 DeserializeAnonymousType .

There's a method DeserializeAnonymousType you can tap in to.

更新 :Json.Net现在包含在ASP.Net中,但是我最近使用的最喜欢的是

Update: Json.Net is now included with ASP.Net, however my latest favorite that I use is JsonFX. It's got great linq support as well, check it out.

更新2 :我已经从JsonFX转移了,目前使用 ServiceStack.Text ,速度很快!

Update 2: I've moved on from JsonFX, and currently use ServiceStack.Text, it's fast!

这篇关于将JSON反序列化为匿名对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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