从下面的 json 对象中,我必须提取值为 true 的所有键。
{
"result": {
"code": 200,
"status": "Success",
"messages": [
"Operation completed successfully."
]
},
"recommendedAction": "NA",
"vendorEvaluationReport": {
"bioCatchEvaluation": {
"sessionId": "79634aa0-1639-11ec-84b0-db18703348d3",
"score": 624,
"fraudEvaluationResult": "tested",
"muid": "1624647875970-F12CF03A-9ADC-4C6E-8F3F-6826220B2607",
"threatIndicators": {
"isBot": false,
"isEmulator": false,
"isRat": false
},
"riskFactors": {
"expertUser": {
"advancedKeyCombo": true
},
"lowDataFamiliarity": {
"importData": true
},
"riskyEvent": {
"recentProfileSettingsChange": true
}
},
"genuineFactors": {
"genuineLocation": {
"consistentIP": true
}
}
}
}
}
我希望提取的值在一个 String array = [advancedKeyCombo, importData, recentProfileSettingsChange, consistentIP]
有人可以帮我解决这个问题吗?
诀窍是遍历 JSON 树并检查每个节点以确定它是否是 BooleanNode。
此代码将生成一个 BooleanNode 类型且具有真值的节点名称列表:
@Test
public void test4() throws JsonProcessingException, IOException {
// https://stackoverflow.com/questions/69224118/java-extract-the-keys-from-json-object-in-to-a-string-whose-values-are-true
final ObjectMapper mapper = new ObjectMapper();
final InputStream jsonStream = getClass().getClassLoader().getResourceAsStream("test4.json");
final JsonNode root = mapper.readTree(jsonStream);
final List<String> nodes = new ArrayList<>();
walkJsonTree("root", root, nodes);
System.out.println(nodes);
}
private void walkJsonTree(final String name, final JsonNode node, final List<String> trueNodes) {
if (node.isObject()) {
final ObjectNode n = (ObjectNode) node;
final Iterator<String> it = n.fieldNames();
while (it.hasNext()) {
final String fn = it.next();
walkJsonTree(fn, n.get(fn), trueNodes);
}
} else if (node.isArray()) {
final ArrayNode n = (ArrayNode) node;
final Iterator<JsonNode> it = n.iterator();
while (it.hasNext()) {
walkJsonTree("array", it.next(), trueNodes);
}
} else if (node.isBoolean()) {
final BooleanNode n = (BooleanNode) node;
if (n.booleanValue()) {
trueNodes.add(name);
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句