从API循环遍历返回的JSON [英] Loop through returned JSON from an API

查看:221
本文介绍了从API循环遍历返回的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在asp.net VB中具有以下JSON:

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?

谢谢

推荐答案

Newtonsoft文档页面使用SelectToken查询JSON 描述一旦加载后如何查询嵌套在JObject层次结构内的值.

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.

例如,使用 SelectTokens() ,您可以查询的注释值如下:

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()

在这里,我使用通配符[*]来匹配"results"数组中的所有元素.这是SelectTokens()支持的 JSONPath查询语法的标准运算符.

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.

这是使用LINQ的等效逻辑:

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()

示例小提琴.

这篇关于从API循环遍历返回的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆