问题
I have the following JSON in asp.net VB:
Dim jsonString As String = "{'results':[ {'comments': 'some text', 'date' : 'some date', 'user':'aaa'},{'comments': 'some text2', 'date2' : 'some date2', 'user':'aaa2'}]} "
Dim json As JObject = JObject.Parse(jsonString)
How can I loop though the values like comments?
Thank you
回答1:
The Newtonsoft documentation pages Querying JSON with LINQ and Querying JSON with SelectToken describe how you can query for values nested inside a JObject
hierarchy once loaded.
For instance, using SelectTokens(), you can query for the comment values as follows:
' Get all comment values, convert them to simple strings, and store in an array:
Dim comments = json.SelectTokens("results[*].comments") _
.Select(Function(t) t.ToString()) _
.ToArray()
Here I am using the wildcard operator [*]
to match all elements in the "results"
array. This is a standard operator of JSONPath query syntax which SelectTokens()
supports.
Here is the equivalent logic using LINQ:
Dim query = From item In json("results")
Let comment = item("comments")
Where comment IsNot Nothing
Select CType(comment, String)
Dim comments = query.ToArray()
Sample fiddle.
来源:https://stackoverflow.com/questions/42819703/loop-through-returned-json-from-an-api