【问题标题】:How to Parse Json grandchild in VB.NET Newtonsoft如何在 VB.NET Newtonsoft 中解析 Json 孙子
【发布时间】:2017-01-21 18:57:49
【问题描述】:

我无法在列表框中显示 tongits,black jack, 21

我只能在列表框中显示最喜欢的游戏,游戏

还有如何计算问卷中的问题数量?


Json 数据

 {
   "id": 1,
   "status": "DRAFT",
   "title": "GAMES",
   "author": "foo",

   "questionnaires": [
          {
           "id": 1,
           "question": "Favorite game",
           "answers": [
                        "tongits",
                        "black jack",
                          "21"
                      ]
           },
         {
          "id": 2,
          "question": "game",
          "answers": [
                       "basketball",
                       "volleyball"
                     ]
          }
      ]
  }

这是我在 VB 中的代码

Dim o As JObject = JObject.Parse(json)

Dim results As List(Of JToken) = o.Children().ToList

For Each item As JProperty In results

item.CreateReader()
Select Case item.Name
    Case "questionnaires"
        Dim question As String
        For Each subitem As JObject In item.Values
            listbox1.item.add(question)
        Next
End Select
Next

很乐意感谢谁会提供帮助

【问题讨论】:

  • 使用JObject.Parse(jsonstring) 那么它就是jobj("questionnaires")(0)("answers").ToArray()
  • 或者,您可以从您的 JSON 中生成一个类型化的类,您可以使用类似 jsonutils.com 的东西。

标签: json vb.net parsing descendant grandchild


【解决方案1】:

您有一个拼写错误“问卷”,因为这在您的 JSON 中不存在(“问卷”存在)。你也不需要搜索它。以下是您可以参考的 Javascript 伪代码。应该与 VB.Net 非常相似。

var jsonData = '{"id": 1,   "status": "DRAFT",  "title": "GAMES",   "author": "foo", "questionnaires": [          {          "id": 1,      "question": "Favorite game",           "answers": [                        "tongits",                        "black jack",                          "21"                      ]           },         {          "id": 2,          "question": "game",          "answers": [                       "basketball",                       "volleyball"                     ]          }      ]  }';    
var jsonObj = JSON.parse(jsonData);
for (var question in jsonObj.questionnaires)
{
  console.log('ID:' + jsonObj.questionnaires[question].id);
  console.log('Question:' + jsonObj.questionnaires[question].question);
  for (var answerToQuestion in jsonObj.questionnaires[question].answers)
  {
    console.log('--->Answer:' + jsonObj.questionnaires[question].answers[answerToQuestion]);
  }
}

结果:

ID:1
Question:Favorite game
--->Answer:tongits
--->Answer:black jack
--->Answer:21
ID:2
Question:game
--->Answer:basketball
--->Answer:volleyball

【讨论】:

  • 感谢循环。最后一个问题,你将如何计算每个问题的答案数?
  • 不需要计算它们,因为答案是一个数组。只需使用数组上的长度属性-> jsonObj.questionnairs [question].answers.length
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多