检索java中json对象的所有嵌套键
如何获取JSON对象的所有嵌套键 下面是JSON输入,它应该返回所有带点分隔的键和子键,如下面的输出 输入:检索java中json对象的所有嵌套键,java,json,algorithm,data-structures,Java,Json,Algorithm,Data Structures,如何获取JSON对象的所有嵌套键 下面是JSON输入,它应该返回所有带点分隔的键和子键,如下面的输出 输入: { "name": "John", "localizedName": [ { "value": "en-US", } ], "entityRelationship": [ { "entity&qu
{
"name": "John",
"localizedName": [
{
"value": "en-US",
}
],
"entityRelationship": [
{
"entity": "productOffering",
"description": [
{
"locale": "en-US",
"value": "New Policy Description"
},
{
"locale": "en-US",
"value": "New Policy Description"
}
]
}
]
}
输出:
["name","localizedName","localizedName.value","entityRelationship","entityRelationship.entity","entityRelationship.description","entityRelationship.description.locale","entityRelationship.description.value"]
[entityRelationship.entity, localizedName, localizedName.value, entityRelationship, name, entityRelationship.description.value, entityRelationship.description, entityRelationship.description.locale]
你可以做:
public void findAllKeys(Object object, String key, Set<String> finalKeys) {
if (object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
jsonObject.keySet().forEach(childKey -> {
findAllKeys(jsonObject.get(childKey), key != null ? key + "." + childKey : childKey, finalKeys);
});
} else if (object instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) object;
finalKeys.add(key);
IntStream.range(0, jsonArray.length())
.mapToObj(jsonArray::get)
.forEach(jsonObject -> findAllKeys(jsonObject, key, finalKeys));
}
else{
finalKeys.add(key);
}
}
@一开始我也这么认为,但请注意,例如,“entityRelationship.description.locale”将在我使用List时出现两次,这与要求相反。@SomeDude根据定义JSON对象中没有顺序。
[entityRelationship.entity, localizedName, localizedName.value, entityRelationship, name, entityRelationship.description.value, entityRelationship.description, entityRelationship.description.locale]