读取 REST API JSON 回复

如何解决读取 REST API JSON 回复

我一直在网络上来回搜索,但找不到我的问题的提示。

我正在通过 RestSharp Client 调用 REST API。我检索了这样的回复:

{
 "meta": {
  "query_time": 0.007360045,"pagination": {
   "offset": 1,"limit": 100,"total": 1
  },"powered_by": "device-api","trace_id": "a0d33897-5f6e-4799-bda9-c7a9b5368db7"
 },"resources": [
  "1363bd6422274abe84826dabf20cb6cd"
 ],"errors": []
}

我现在想查询 resources 的值。这是我使用的代码:

Dim id_request = New RestRequest("/devices/queries/devices/v1?filter=" + filter,Method.GET)
id_request.AddHeader("Accept","application/json")
id_request.AddHeader("Authorization","bearer " + bearer)
Dim data_response = data_client.Execute(id_request)
Dim data_response_raw As String = data_response.Content
Dim raw_id As JObject = JObject.Parse(data_response_raw)
Dim id = raw_id.GetValue("resources").ToString

不幸的是,我只收到了 ["1363bd6422274abe84826dabf20cb6cd"] 而不是 1363bd6422274abe84826dabf20cb6cd

谁能指出我正确的方向?

我也尝试过使用 JsonConvert.DeserializeObject() 进行反序列化,但不知何故失败了。

我在这里找到了这个解决方案,但是如果我尝试重建它会失败,因为它无法识别字典部分

 Dim tokenJson = JsonConvert.SerializeObject(tokenJsonString)
 Dim jsonResult = JsonConvert.DeserializeObject(Of Dictionary(Of String,Object))(jsonString)
 Dim firstItem = jsonResult.Item("data").Item(0)

编辑:

当尝试按照建议反序列化根目录但似乎第二个响应是嵌套的 JSON 时。

我有这样的回复:

dr = {
     "meta": {
      "query_time": 0.004813129,"trace_id": "5a355c86-37f7-416d-96c4-0c8796c940fc"
     },"resources": [
      {
       "device_id": "1363bd6422274abe84826dabf20cb6cd","policies": [
        {
         "policy_type": "prevention","policy_id": "1d34205a4e2c4d1991431c037c8e5734","applied": true,"settings_hash": "7cb00a74","assigned_date": "2021-02-22T13:56:37.759459481Z","applied_date": "2021-02-22T13:57:19.962692301Z","rule_groups": []
        }
       ],"meta": {
        "version": "352"
       }
      }
     ],"errors": []
    }

我尝试过:

Dim restApiResponse = JsonConvert.DeserializeObject(Of RestApiResponseRoot)(dr)
' This is your array of strings
Dim resources = restApiResponse.Resources

不幸的是我得到 Newtonsoft.Json.JsonReaderException: '解析值时遇到意外字符:{.路径“资源”,第 8 行,位置 3。'

解决方法

资源属性是一个数组。像往常一样,您需要指定要考虑的数组元素。在这种情况下,第一个,即索引0处的元素。

Dim jsonObject = JObject.Parse(data_response_raw)
Dim firstResource = jsonObject("resources")(0).ToString()

如果您希望将数组内容作为字符串数组,而不仅仅是第一个元素 - 假设 resources 可以包含多个字符串(毕竟它是一个数组) - 反序列化为 String()

Dim jsonObject = JObject.Parse(data_response_raw)
Dim resources = JsonConvert.DeserializeObject(Of String())(jsonObject("resources").ToString())

如果您需要整个 JSON 响应,我建议反序列化为表示 JSON 的类 Model:

Public Class RestApiResponseRoot
    Public Property Meta As Meta
    Public Property Resources As List(Of String)
    Public Property Errors As List(Of Object)
End Class
Public Class Meta
    <JsonProperty("query_time")>
    Public Property QueryTime As Double
    Public Property Pagination As Pagination
    <JsonProperty("powered_by")>
    Public Property PoweredBy As String
    <JsonProperty("trace_id")>
    Public Property TraceId As Guid
End Class
Public Class Pagination
    Public Property Offset As Long
    Public Property Limit As Long
    Public Property Total As Long
End Class

然后您可以反序列化模型的根对象 - 此处名为 RestApiResponseRoot 的类 - 并像往常一样访问其属性:

Dim restApiResponse = JsonConvert.DeserializeObject(Of RestApiResponseRoot)(
    data_response_raw
)
' This is your array of strings
Dim resources = restApiResponse.Resources

另一个 JSON 响应略有不同,响应属性包含一个对象数组而不是字符串。
添加了更多属性和嵌套对象。您只需要调整模型。

Public Class RestApiResponseRoot2
    Public Property Meta As RootObjectMeta
    Public Property Resources As List(Of Resource)
    Public Property Errors As List(Of Object)
End Class

Public Class RootObjectMeta
    <JsonProperty("query_time")>
    Public Property QueryTime As Double
    <JsonProperty("powered_by")>
    Public Property PoweredBy As String
    <JsonProperty("trace_id")>
    Public Property TraceId As Guid
End Class

Public Class Resource
    <JsonProperty("device_id")>
    Public Property DeviceId As String
    Public Property Policies As List(Of Policy)
    Public Property Meta As ResourceMeta
End Class

Public Class ResourceMeta
    Public Property Version As String
End Class

Public Class Policy
    <JsonProperty("policy_type")>
    Public Property PolicyType As String
    <JsonProperty("policy_id")>
    Public Property PolicyId As String
    Public Property Applied As Boolean
    <JsonProperty("settings_hash")>
    Public Property SettingsHash As String
    <JsonProperty("assigned_date")>
    Public Property AssignedDate As DateTimeOffset
    <JsonProperty("applied_date")>
    Public Property AppliedDate As DateTimeOffset
    <JsonProperty("rule_groups")>
    Public Property RuleGroups As List(Of Object)
End Class

Dim restApiResponse2 = JsonConvert.DeserializeObject(Of RestApiResponseRoot2)(dr)
Dim resources As List(Of Resource) = restApiResponse2.Resources
' DeviceId of the first Resources object
Dim deviceId = resources(0).DeviceId

您可以使用一些在线资源来处理您的 JSON 对象:

JSON Formatter & Validator

QuickType - JSON 到 .Net 类 - C#,没有 VB.Net

JSON Utils - JSON 到 .Net 类 - 包括 VB.Net。比 QuickType 功能稍差

,

尝试在输出的第一个和最后一个字符中使用 " 字符修剪资源值

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res