在 vb.net 中反序列化 json 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4868863/
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
Deserialize json array in vb.net
提问by Cyclone
I have a json array which is formatted as follows:
我有一个 json 数组,其格式如下:
[
{
"property":96,
"listofstuff":[
{
"anotherproperty":"some text here",
"yetanother":"text goes here too"
}
],
"lastproperty":3001
},
<rest of array>
]
How can I deserialize this in such a way that I can have a list of objects indexed by property? Meaning, I want to be able to access the data like this: MyList(96).lastpropertyor MyList(96).listofstuff.yetanotherand have it return the proper datatype too? Is that even possible in vb.net?
我怎样才能以这样的方式反序列化它,以便我可以得到一个由 索引的对象列表property?意思是,我希望能够像这样访问数据:MyList(96).lastproperty或者MyList(96).listofstuff.yetanother让它也返回正确的数据类型?这在 vb.net 中甚至可能吗?
采纳答案by Enigmativity
I agree that the JSON library you need to use is Json.NET found at http://json.codeplex.com/
我同意您需要使用的 JSON 库是在http://json.codeplex.com/ 上找到的 Json.NET
So, given your example JSON array, I made the following classes that can be used for serializing and deserializing:
因此,鉴于您的示例 JSON 数组,我创建了以下可用于序列化和反序列化的类:
Public Class Item
Public Property [property]() As Integer
Public Property listofstuff() As Stuff()
Public Property lastproperty() As Integer
End Class
Public Class Stuff
Public Property anotherproperty() As String
Public Property yetanother() As String
End Class
Then all you need is the following code to be able to access the data in roughly the way you wanted to:
然后,您只需要以下代码即可大致按照您想要的方式访问数据:
Dim Items = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Item())(json)
Dim MyList = Items.ToDictionary(Function(x) x.property)
Dim Stuff = MyList(96).listofstuff(0)
If your intent with the listofstuffproperty array was to store any string pair then use this definition for Item(and you also won't need the Stuffclass):
如果您对listofstuff属性数组的意图是存储任何字符串对,则将此定义用于Item(并且您也不需要Stuff该类):
Public Class Item
Public Property [property]() As Integer
Public Property listofstuff() As Dictionary(Of String, String)()
Public Property lastproperty() As Integer
End Class
回答by Sean
You need a JSON library for .net: http://json.codeplex.com/
你需要一个 .net 的 JSON 库:http: //json.codeplex.com/

