我有嵌套的JSON字符串,我想从下面这样的字符串中解析出合适的值。在我不断学习的过程中,我有点挣扎,我的第一部分工作是,我可以解析出单个JSON字符串,并使用下面的代码示例1返回适当的值,但我遇到了一个JSON字符串,因为它是嵌套的,所以同样的方法不适用于
{
"jsonrpc":"2.0",
"method":"Player.OnPause",
"params":{
"data": { "item": { "id":29, "type":"episode" },
"player": { "playerid":1, "speed":0 }
},
"sender":"xbmc"
}
}
代码。。。
Dim JSON As String
Dim values As Newtonsoft.Json.Linq.JObject
JSON = JSON STRING WOULD GO HERE, COMES from TCP IP STREAM
values = JObject.Parse(JSON)
Console.WriteLine(values.GetValue("method"))
使用该示例,我可以从一级JSON字符串中提取方法键(例如Player.OnPause),但我如何从二级和三级字符串中提取数据,例如在上面的字符串中,能够获得数据级JSON值和项目级JSON值。这可能与上述类似吗?
感谢您提供的任何提示,我是一个通过示例学习的人,但只是在努力应用一些东西来读取多个嵌套的JSON字符串或多个级别。毫无疑问,这将是一件容易的事情,我错过了,但我感谢任何人能提供的帮助。
感谢
Dim jsonstring = IO.File.ReadAllText("json.txt")
Dim jo = Json.Linq.JObject.Parse(jsonstring)
Dim playerid = jo("params")("data")("player")("playerid")
你的意思是这样的吗?"json.txt"只包含您的json字符串。
在这里和其他地方搜索了一个将javascrip对象表示法解析到.net词典中的多语言示例后,我放弃了,写了自己的词典。希望有人觉得这很有用;)
Public Class jsonDictionary
Inherits Dictionary(Of String, Object)
#Region "Public Properties"
Private _parent As jsonDictionary
Public ReadOnly Property Parent() As jsonDictionary
Get
Return _parent
End Get
End Property
#End Region
#Region "Initialisation and Finalisation"
Public Sub New(ByVal Parent As jsonDictionary, ByVal strJson As String)
_parent = Parent
For Each Element As String In SplitJSON(CharTrim(strJson))
Dim elName As String = CharTrim(Element.Split(":")(0).Trim)
Select Case Element.Split(":")(1).Trim.Substring(0, 1)
Case "{"
Me.Add(elName, New jsonDictionary(Me, Element.Substring(InStr(Element, ":"))))
Case "["
Dim ElArray As New List(Of jsonDictionary)
For Each ArrayElement As String In SplitJSON(CharTrim(Element.Substring(InStr(Element, ":"))))
ElArray.Add(New jsonDictionary(Me, ArrayElement))
Next
Me.Add(elName, ElArray)
Case Else
Me.Add(elName, Element.Split(":")(1).Trim)
End Select
Next
End Sub
#End Region
#Region "Private Methods"
Public Shared Function CharTrim(ByVal Str As String) As String
Return Str.Trim.Substring(1, Str.Length - 2)
End Function
Private Function SplitJSON(ByVal str As String) As String()
Dim ret() As String = Nothing
Dim sqCount As Integer = 0
Dim clCount As Integer = 0
Dim buildStr As New System.Text.StringBuilder
For i As Integer = 0 To str.Length - 1
Select Case str.Substring(i, 1)
Case ","
If sqCount = 0 And clCount = 0 Then
Try
ReDim Preserve ret(UBound(ret) + 1)
Catch ex As Exception
ReDim ret(0)
Finally
ret(UBound(ret)) = buildStr.ToString
buildStr = New System.Text.StringBuilder
End Try
Else
buildStr.Append(str.Substring(i, 1))
End If
Case Else
buildStr.Append(str.Substring(i, 1))
Select Case str.Substring(i, 1)
Case "["
sqCount += 1
Case "]"
sqCount -= 1
Case "{"
clCount += 1
Case "}"
clCount -= 1
End Select
End Select
Next
If buildStr.ToString.Length > 0 Then
Try
ReDim Preserve ret(UBound(ret) + 1)
Catch ex As Exception
ReDim ret(0)
Finally
ret(UBound(ret)) = buildStr.ToString
End Try
End If
Return ret
End Function
#End Region
End Class