[英]Get all key-value pair from nested JSON array
嗨,我有一個嵌套的 JSON 也有 JSON 陣列。 我需要所有單個鍵值對。 下面是嵌套的 JSON,其中有一些 JSON arrays。
{
"relatedquoteresponse":{
"responsepreamble":{
"responseStatus":"Passed",
"statusCode":"200"
},
"phone":null,
"symbol":"$",
"retrieverelatedquotes":[
{
"quoteId":23232
},
{
"quoteName":"Netally-Service"
}
],
"CheckStatus":{
"StatusCode":200,
"responseMessage":"Found"
}
}
}
我需要這樣的 output:
responseStatus : "Passed"
statusCode : "200"
Phone: null
symbol: "$"
quoteID: 23232
quoteName: "Netally-Service"
我嘗試了下面的代碼,但得到了這個 output。
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(json);
Iterator<String> iterator = jsonNode.fieldNames();
while (iterator.hasNext()) {
String key = iterator.next();
printRec(jsonNode, key);
}
public static void printRec(JsonNode jsonNode, String key) {
JsonNode node = jsonNode.get(key);
if (node.isObject()) {
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
fields.forEachRemaining(field -> {
printRec(node, field.getKey());
if (!field.getValue().isObject()) {
System.out.println(field.getKey() + " : " + field.getValue());
}
});
}
}
OutPut:
responseStatus : "Passed"
statusCode : "200"
Phone: null
symbol: "$"
retrieverelatedquotes : [{"quoteId":23232},{"quoteName":"Netally-Service"}]
任何人都可以幫助我獲得所有不在上面數組中的鍵值對。
謝謝
遞歸確實有幫助,甚至適用於多個級別。
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(json);
printRec(jsonNode, "");
----------
public static void printRec(JsonNode jsonNode, String key) {
if (jsonNode.isValueNode()) {
System.out.println(key + " : " + jsonNode);
} else if (jsonNode.isObject()) {
jsonNode.fields().forEachRemaining(field -> printRec(field.getValue(), field.getKey()));
} else if (jsonNode.isArray()) {
for (int i = 0; i < jsonNode.size(); i++) {
printRec(jsonNode.get(i), key + "[" + i + "]");
}
}
}
Output
responseStatus : "Passed"
statusCode : "200"
phone : null
symbol : "$"
quoteId : 23232
quoteName : "Netally-Service"
StatusCode : 200
responseMessage : "Found"
您可以使用 Regex 命名組功能來獲取所有單個鍵和值
Pattern pattern = Pattern.compile("\"(.+)\":(?![{\\[])(.+)");
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
System.out.println(matcher.group(1) + " : " + matcher.group(2));
}
Output 將是:
responseStatus : "Passed",
statusCode : "200"
phone : null,
symbol : "$",
quoteId : 23232
quoteName : "Netally-Service"
StatusCode : 200,
responseMessage : "Found"
您可以輕松修改模式以獲取所有具有 int 值的單個鍵,例如 null 值
關於正則表達式命名組和反向引用的簡單文章
問題不是很清楚。 那么,如果你得到一個真正的陣列,你打算如何管理它? 無論如何,最簡單的方法是創建 POJO object 進行映射,並創建 map JSON 到這個 ZA8CFDE6331BD59EB2AC9C46F8Z
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.