簡體   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