C# - 反序列化到JSON匿名对象 [英] C# - Deserialize JSON to anonymous object
问题描述
在C#中,我已经成功地序列化一个匿名对象成JSON通过使用code像这样的...
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());
但是,这会产生一个错误:
But this produces an error:
类型'&LT的定义无参数的构造函数;> f__AnonymousType0`2 [System.Int32,mscorlib程序,版本= 4.0.0.0,文化=中性公钥= b77a5c561934e089],[System.String,mscorlib程序,版本= 4.0 .0.0,文化=中性公钥= 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,但我最喜欢的最新的,我用的是的 JsonFX 。它有很大的LINQ支持,以及,检查出来。
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!
这篇关于C# - 反序列化到JSON匿名对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!