我是JSON的新手,无法解决以下问题:
我正在从第三方程序获取JSON文件。 JSON如下所示:
{
"Name 1": {
"Property 1": 154600,
"Property 2": true,
"Property 3": 5340,
"Property 4": 54634
},
"Name 2": {
"Property 1": 5436,
"Property 2": false,
"Property 3": 45678769,
"Property 4": 2342342
}
}
我需要在Listview中获取它们,并为每个属性和名称添加一列。
我通过JSONUtils网站生成了一个类:
Public Class Name1
<JsonProperty("Property 1")>
Public Property Property1 As Integer
<JsonProperty("Property 2")>
Public Property Property2 As Boolean
<JsonProperty("Property 3")>
Public Property Property3 As Integer
<JsonProperty("Property 4")>
Public Property Property4 As Integer
End Class
Public Class Name2
<JsonProperty("Property 1")>
Public Property Property1 As Integer
<JsonProperty("Property 2")>
Public Property Property2 As Boolean
<JsonProperty("Property 3")>
Public Property Property3 As Integer
<JsonProperty("Property 4")>
Public Property Property4 As Integer
End Class
Public Class NameList
<JsonProperty("Name 1")>
Public Property Name1 As Name1
<JsonProperty("Name 2")>
Public Property Name2 As Name2
End Class
但是由于名称的更改,我不得不在运行时动态添加这些类。
接下来,我尝试生成一个看起来像这样的类:
Public Class NameList
Public Property Name As String
<JsonProperty("Property 1")>
Public Property Property1 As Integer
<JsonProperty("Property 2")>
Public Property Property2 As Boolean
<JsonProperty("Property 3")>
Public Property Property3 As Integer
<JsonProperty("Property 4")>
Public Property Property4 As Integer
End Class
这是预期的,但是当我运行测试程序时,出现错误:
System.NullReferenceException: "Object reference not set to an instance of an object."
在我的代码下面:
Dim client As New WebClient()
Dim stream As Stream = client.OpenRead("C:\\Filename.json")
Dim reader As New StreamReader(stream)
Dim jsonData As String = reader.ReadToEnd
reader.Close()
Dim allData As JObject = JObject.Parse(jsonData)
Dim nameDataList As New List(Of NameList)
For Each token As JToken In allData("")
Dim prop As JProperty = token
If Not prop.Name.StartsWith("_") Then
nameDataList.Add(New NameList With {
.Name = prop.Name,
.Property1 = prop.Value("Property 1"),
.Property2 = prop.Value("Property 2"),
.Property3 = prop.Value("Property 3"),
.Property4 = prop.Value("Property 4")})
End If
Next
之后是将令牌添加到我的Listview的代码。
此行出现错误:
For Each token As JToken In allData("")
如何避免此错误?
预先感谢:)
答案 0 :(得分:0)
allData(“”)没有任何JToken。是[string,JToken]的KeyValuePair。
尝试从代码和As JToken中删除(“”)。像这样:
For Each obj As KeyValuePair In allData
Dim name As String = obj.Key
Dim token As JToken = obj.Value
Next