Loop through returned JSON from an API

£可爱£侵袭症+ 提交于 2020-01-25 21:25:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!