【问题标题】:VB.net 2005 Convert JSON Object to Array ListVB.net 2005 将 JSON 对象转换为数组列表
【发布时间】:2018-10-11 13:45:41
【问题描述】:

我无法从“list”中获取“kode”作为该对象的数组。

{
           "metaData":{
              "code":"200",
              "message":"Sukses"
           },
           "response":{
              "list":[
                 {
                    "kode":"31486",
                    "nama":"Satro Jadhit, dr"
                 },
                 {
                    "kode":"31492",
                    "nama":"Satroni Lawa, dr"
                 }
              ]
           }
        }

我可以从 JSON 中获取除数组之外的任何内容。 我试过使用这个解决方案 [How to read JSON http post response using VB

还有其他解决方案,但我的 vb 没有 newtonsoft json 的某些功能。 我使用 Visual Studio 2005,.net 框架 2.0

那么,我如何将它作为我的数组。

编辑

这是我尝试过的,我可以从“列表”中获得价值 (我用的是别的代码,所以这个值不一样)

Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

Dim kodeDpjp as string

Dim json As String = responseFromServer
Dim serObj As Newtonsoft.Json.Linq.JObject = 
         Newtonsoft.Json.Linq.JObject.Parse(json)
Dim token As Newtonsoft.Json.Linq.JToken = serObj.SelectToken("response") 
         ("list")
If (token.GetType() Is GetType(Newtonsoft.Json.Linq.JArray)) Then
    Console.WriteLine(token)
End If

这就是结果

[
  {
    "kode": "8784",
    "nama": "drg.MELANI SARI TANJUNG"
  },
  {
    "kode": "8848",
    "nama": "drg.ARIEF KURNIAWAN"
  },
  {
    "kode": "8873",
    "nama": "drg.SRI ARIANI SUGIARTI"
  }
]

我只想在组合框中为我的数组“kode”

谢谢

【问题讨论】:

  • 我已尝试使用此解决方案... 在这种情况下,请edit 分享您尝试但无效的问题。原因请参阅How to Ask,它建议帮助他人重现问题
  • @BrianRogers 我使用 json.net .net 2.0
  • @dbc 谢谢,我已经编辑了我的问题。

标签: arrays json vb.net json.net visual-studio-2005


【解决方案1】:

由于您知道serObj.SelectToken("response")("list") 的结果是JArray,因此您可以使用CType 对其进行转换,然后使用For Each 循环来迭代这些项目。这里的每一项都是一个JObject,您可以使用索引器方法来获取属性值。然后您可以再次使用CType 将这些值转换为字符串。

代码如下:

' Parse the JSON to a JObject
Dim serObj As JObject = JObject.Parse(json)

' Retrieve the list and cast it to a JArray
Dim list As JArray = CType(serObj.SelectToken("response")("list"), JArray)

' Loop over the items in the array (each is a JObject)
For Each item As JObject In list

    ' Get the "kode" property from the JObject and convert it to a string
    Dim kode As String = CType(item("kode"), String)

    ' Get the "nama" property from the JObject and convert it to a string
    Dim nama As String = CType(item("nama"), String)

    ' You can add kode and/or nama to your ComboBox here
Next

小提琴:https://dotnetfiddle.net/lkrWa4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-18
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 2013-06-25
    • 2016-10-06
    相关资源
    最近更新 更多