将 json 数组反序列化为 .net 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2272111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deserializing json array into .net class
提问by GordonB
I'm having problems deserializing some json data, getting InvalidCastExceptions and the like.
我在反序列化一些 json 数据、获取 InvalidCastExceptions 等方面遇到问题。
Can anyone point me in the right direction?
任何人都可以指出我正确的方向吗?
Here's the json i'm wanting to deserialize;
这是我想要反序列化的 json;
[{"OrderId":0,"Name":"Summary","MaxLen":"200"},{"OrderId":1,"Name":"Details","MaxLen":"0"}]
[{"OrderId":0,"Name":"Summary","MaxLen":"200"},{"OrderId":1,"Name":"Details","MaxLen":"0"}]
Here's my code;
这是我的代码;
Public Class jsTextArea
Public OrderId As Integer
Public Name As String
Public MaxLen As String
End Class
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim rawdata = js.DeserializeObject(textAreaJson)
Dim lstTextAreas As List(Of jsTextArea) = CType(rawdata, List(Of jsTextArea))
回答by Rob
OrderId is an Int in your json (note the lack fo quotes round the values), but you're declaring it as String in "jsTextArea". Also, unless the type that rawdata is returned as has a cast to List(Of jsTextArea), which it probably doesn't the code you've shown won't work.
OrderId 是您的 json 中的一个 Int(注意缺少围绕值的引号),但是您在“jsTextArea”中将其声明为 String。此外,除非原始数据返回的类型具有转换为 List(Of jsTextArea) 的类型,否则您显示的代码可能不起作用。
UpdateTo get the data out into a List(Of jsTextArea) try the following:
更新要将数据放入 List(Of jsTextArea) 中,请尝试以下操作:
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim lstTextAreas = js.Deserialize(Of List(Of jsTextArea))(textAreaJson)
回答by GordonB
Doing it all on one line worked a treat;
在一条线上完成所有工作是一种享受;
Dim lstTextAreas As List(Of jsTextArea) = js.Deserialize(textAreaJson, GetType(List(Of jsTextArea)))
回答by Sky Sanders
Dim textAreaJson As String = "[{""OrderId"":0,""Name"":""Summary"",""MaxLen"":""200""},{""OrderId"":1,""Name"":""Details"",""MaxLen"":""0""}]"
Dim js As New System.Web.Script.Serialization.JavaScriptSerializer
Dim lstTextAreas As jsTextArea() = js.Deserialize(Of jsTextArea())(textAreaJson)
回答by mikro
Here's a function to Deserialize JSON of any type:
这是一个反序列化任何类型的 JSON 的函数:
Public Function DeserializeJson(Of T)(json As String) As T
Return New JavaScriptSerializer().Deserialize(Of T)(json)
End Function

