繁体   English   中英

从 java 中的 api 解析 JSON 数组

[英]Parse JSON Array from an api in java

我有一个 api,它给了我这个 json 数组。 我如何获取 traceId 的特定键值对? 这些是 zipkin 生成的痕迹,但我想将它们存储到数据库中,因为它们不会持久存在。

[
{
"traceId": "ffd089581fd99e76f7651c39d4e04077",
"id": "67a5d3b4654af838",
"kind": "CLIENT",
"name": "calllocal/service-c/test",
"timestamp": 1652492570462066,
"duration": 2000513,
"localEndpoint": {
"serviceName": "service-c",
"ipv4": "192.168.86.55"
},
"tags": {
"dapr.api": "GET /v1.0/invoke/service-c/method/test",
"dapr.protocol": "http",
"dapr.status_code": "500",
"error": "INTERNAL",
"net.peer.name": "service-c",
"opencensus.status_description": "Internal",
"rpc.service": "ServiceInvocation"
}
},
{

"traceId": "bcf880b8d37b2b3ec0ebb35ab461fabc",
"id": "82d26de7de56edf3",
"kind": "CLIENT",
"name": "calllocal/service-c/test",
"timestamp": 1652492570459897,
"duration": 2002253,
"localEndpoint": {
"serviceName": "service-c",
"ipv4": "192.168.86.55"
},
"tags": {
"dapr.api": "GET /v1.0/invoke/service-c/method/test",
"dapr.protocol": "http",
"dapr.status_code": "500",
"error": "INTERNAL",
"net.peer.name": "service-c",
"opencensus.status_description": "Internal",
"rpc.service": "ServiceInvocation"
}
}
]

这是我到目前为止所拥有的,但它不起作用。 我尝试了其他一些方法,但没有成功。感谢任何帮助

{
URL url = new URL("http://localhost:9411/zipkin/api/v2/traces?");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();

//Getting the response code
int responsecode = conn.getResponseCode();


if (responsecode != 200)
{
    throw new RuntimeException("HttpResponseCode: " + responsecode);
}
else
{

String inline = "";
Scanner scanner = new Scanner(url.openStream());

//Write all the JSON data into a string using a scanner
while (scanner.hasNext())
{
    inline += scanner.nextLine();
}

//Close the scanner
scanner.close();


JSONParser jsonParser = new JSONParser();

JSONObject jsonObject = (JSONObject) jsonParser.parse(inline);
String value = (String) jsonObject.get("traceId");
System.out.println(value);
  }
}

对于代码:

JSONParser jsonParser = new JSONParser();

JSONObject jsonObject = (JSONObject) jsonParser.parse(inline);
String value = (String) jsonObject.get("traceId");
System.out.println(value);
  }
}

看起来你需要解析一个 JSONArray。 并迭代它们,以获得每个的“traceId”。

JSONArray array= JSONArray.parseArray(....);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM