当您没有类型时,如何在 .NET 中反序列化 JSON 字符串
检查此 URL:
http://api.stackoverflow.com/1.1/users/811785/questions? sort=votes
这是来自 StackOveflow 的 API 的 URL。返回的 JSON 非常复杂,我想将其转换为一个对象,以便我可以在 ASP.NET MVC 的视图中使用它。
问题在于,JavaScriptSerializer
对象的 Deserialize
方法采用 Type
参数作为其第二个参数。但返回的 JSON 非常复杂,我不想创建强类型对象来反序列化它。
我应该怎么办?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在.NET 4.0中,您可以在此处使用动态
更多
http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx
这里还有更多
http://dynamicjson.codeplex.com/
in .NET 4.0, you can using dynamic
More here
http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx
And more here
http://dynamicjson.codeplex.com/
使用 Json.NET 你可以做这样的事情
With Json.NET you can do something like this
您不需要像 JSON.NET 这样的额外库,只需使用 JavaScriptSerializer 即可。
您可以考虑
JavaScriptSerializer.DeserializeObject
,它将返回一个Object
,它基本上是一个Dictionary
。您必须继续转换才能获得嵌套值。
在快速观察中查看反序列化对象,然后您就会知道到底需要什么来转换返回的
Dictionary
You don't need an extra library like JSON.NET and just work with JavaScriptSerializer.
You may consider
JavaScriptSerializer.DeserializeObject
which will return anObject
which is basically aDictionary<string, object>
.You have to keep on casting to get the nested value.
See the deserialized object in your Quick Watch, then you will know what exactly you need to cast your returned
Dictionary<>
尝试
System.Web.Script.JavascriptSerializer
它有许多Deserialize
重载方法,使用它,你一定会得到你想要的。Try
System.Web.Script.JavascriptSerializer
which is having manyDeserialize
overloaded methods, play with it, and you will surely get what you want.