我有一個來自 HTTP 呼叫的以下回應,看起來像這樣......
[{"id": 1, "name" : abc, "above50" : true} , {"id": 2, "name" : "xyc", "above50" : false, "kids" : "yes"} ]
我需要遍歷這個串列并查找是否有一個名為 kids 的密鑰,如果有密鑰 kids,我需要存盤該值。我如何在Java中做到這一點?
uj5u.com熱心網友回復:
首先,您需要決議 json 字串——它是一個物件串列。如果您沒有匹配這些物件的類,默認情況下它們可以表示為Map<String, Object>. 然后你需要迭代串列,并且對于其中的每個物件,你必須迭代物件中的條目。如果密鑰匹配,則存盤它。
//parse json string with whatever parser you like
List<Map<String, Object>> list = ...;
//iterate every object in the list
for (Map<String, Object> map : list) {
//iterate every entry in the object
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals("kids")) {
//you can store the key and the value however you want/need
System.out.println(entry.getKey() " -> " entry.getValue());
}
}
}
uj5u.com熱心網友回復:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
-------------------------------------------
@Test
public void test04() throws IOException {
final String preString = "[{\"id\": 1, \"name\" : \"abc\", \"above50\" : true} , {\"id\": 2, \"name\" : \"xyc\", \"above50\" : false, \"kids\" : \"yes\"} ]";
final ObjectMapper objectMapper = new ObjectMapper();
final JsonNode arrayNode = objectMapper.readTree(preString);
if (arrayNode.isArray()) {
for (JsonNode it : arrayNode) {
final JsonNode kids = it.get("kids");
if (kids != null) {
//TODO: Storage this value by you want
System.out.println(kids.asText());
}
}
}
}
uj5u.com熱心網友回復:
您可以使用 JSONObject 或 JSONArray
String message = ""list" : [{"id": 1, "name" : abc, "above50" : true} , {"id": 2, "name" : "xyc", "above50" : false, "kids" : "yes"} ]";
JSONObject jsonObject = new JSONObject(message);
JSONArray array = jsonObject.getJsonArray("list");
//so now inside the jsonArray there is 2 jsonObject
//then you can parse the jsonArray and check if there is
//a jsonObject that have "kids" like jsonObject.get("kids") != null
// or jsonObject.getString("kids") != null
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/419225.html
標籤:
上一篇:如何將串列中的資訊轉換為表格?
下一篇:將兩個串列轉換為R中的資料框
