【问题标题】:Deserialize json array in vb.net在 vb.net 中反序列化 json 数组
【发布时间】:2011-06-19 15:00:09
【问题描述】:

我有一个 json 数组,格式如下:

[
  {
    "property":96,
    "listofstuff":[
      {
        "anotherproperty":"some text here",
        "yetanother":"text goes here too"
      }
    ],
    "lastproperty":3001
  },
 <rest of array>
]

我怎样才能反序列化它以使我可以拥有由property 索引的对象列表?意思是,我希望能够访问这样的数据:MyList(96).lastpropertyMyList(96).listofstuff.yetanother 并让它也返回正确的数据类型?这在 vb.net 中是否可行?

【问题讨论】:

  • 我实际上曾尝试用正则表达式解析它,事后看来这似乎不是最聪明的方法......

标签: vb.net arrays json deserialization


【解决方案1】:

我同意您需要使用的 JSON 库是位于 http://json.codeplex.com/ 的 Json.NET

因此,给定您的示例 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

那么您只需要以下代码就能够以您想要的大致方式访问数据:

Dim Items = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Item())(json)
Dim MyList = Items.ToDictionary(Function(x) x.property)
Dim Stuff = MyList(96).listofstuff(0)

如果您对 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

【讨论】:

  • Items.ToDictionary 好像不存在?
  • 另外,如果这段代码像看起来那样简单,那么你已经为我节省了几个小时调试丑陋正则表达式的时间。
  • 从头开始。我忘了一个括号。
【解决方案2】:

您需要一个用于 .net 的 JSON 库:http://json.codeplex.com/

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-09-06
  • 1970-01-01
  • 2011-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-01
相关资源
最近更新 更多