'Parse JSON Array from an api in java
I have an api that gives me this json array. How do i just get specific key value pairs for traceId? these are traces generated by zipkin but i want to store them to a database since they do not persist.
[
{
"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"
}
}
]
This is what i have so far but it is not working. I have tried a few other methods but no success.Any help is appreciated
{
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);
}
}
Solution 1:[1]
For the code:
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(inline);
String value = (String) jsonObject.get("traceId");
System.out.println(value);
}
}
Looks like you need to parse a JSONArray. and iterate them, to get the "traceId" for each.
JSONArray array= JSONArray.parseArray(....)?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SeanH |
