gpt4 book ai didi

java - 如何在java中从Json对象中获取元素

转载 作者:行者123 更新时间:2023-12-02 09:07:12 25 4
gpt4 key购买 nike

这是我调用 API 时的 json 对象

工作

{
"path": "/",
"isBase64Encoded": false,
"requestContext": {
"resourceId": "20gm43r4fa",
"resourcePath": "/",
"httpMethod": "POST",
"extendedRequestId": "GO6ktGL_IAMFaLA=",
"requestTime": "13/Jan/2020:09:53:34 +0000",
"path": "/",
"accountId": "***",
"protocol": "HTTP/1.1",
"stage": "test-invoke-stage",
"domainPrefix": "testPrefix",
"requestTimeEpoch": 1578909214062,
"requestId": "dgdfg-ad12-431a-b1b9-***",
"identity": {
"accountId": "***",
"caller": "345345:a.b@***.com",
"apiKey": "test-invoke-api-key",
"sourceIp": "test-invoke-source-ip",
"accessKey": "&&YY&&YH",
"userArn": "arn:aws:sts::***:assumed-role/****-PowerUser/ab.dx@****.com",
"apiKeyId": "test-invoke-api-key-id",
"userAgent": "aws-internal/3 aws-sdk-java/1.11.690 Linux/4.9.184-0.1.ac.235.83.329.metal1.x86_64 OpenJDK_64-Bit_Server_VM/25.232-b09 java/1.8.0_232 vendor/Oracle_Corporation",
"user": "345345345:Sa.b@***.com"
},
"domainName": "testPrefix.testDomainName",
"apiId": "dfgdf"
},
"resource": "/",
"httpMethod": "POST",
"body": "{\"ID\":\"sup-9749-0e710000fd04\",\"VERSION\":1,\"AUDIT_EVENT_TO_DATE_TP\":null}"
}

JSON 的主体是这样的

bodyofJson

{
"ID": "sup-9749-0e710000fd04",
"VERSION": 1,
"ACTION_TYPE": "NEW_CASE",
"EVENT_TYPE": "WORLDCHECK"
}

我需要获取 json 的正文和作为 ID 的 key ,该 ID 位于 Body json 内。我能够获取 Body,但无法从 body json 获取 ID

这就是我正在做的

JSONObject job = new JSONObject(json);
System.out.println("****job*******"+job);
String bodyofJson = job.getString("body");
System.out.println("****bodyofJson*******"+bodyofJson);

ID 的位置也可能会发生变化,这就是为什么我没有基于索引

请提出建议

最佳答案

body 键还包含一个 json。因此,我们需要将其解析为 JSONObject 并获取 ID 的值。

这是代码:

JSONObject job = new JSONObject(json);
System.out.println("****job*******"+job);
String bodyofJson = job.getString("body");
System.out.println("****bodyofJson*******"+bodyofJson);
// Parse bodyofJson as JSONObject
JSONObject bodyJsonObj = new JSONObject(bodyofJson);
System.out.println(bodyJsonObj.get("ID"));

关于java - 如何在java中从Json对象中获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59714399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com