এটি সমস্যার আরেকটি কার্যক্ষম সমাধান:
public void test (){
Map<String, String> keyValueStore = new HasMap<>();
Stack<String> keyPath = new Stack();
JSONObject json = new JSONObject("thisYourJsonObject");
keyValueStore = getAllXpathAndValueFromJsonObject(json, keyValueStore, keyPath);
for(Map.Entry<String, String> map : keyValueStore.entrySet()) {
System.out.println(map.getKey() + ":" + map.getValue());
}
}
public Map<String, String> getAllXpathAndValueFromJsonObject(JSONObject json, Map<String, String> keyValueStore, Stack<String> keyPath) {
Set<String> jsonKeys = json.keySet();
for (Object keyO : jsonKeys) {
String key = (String) keyO;
keyPath.push(key);
Object object = json.get(key);
if (object instanceof JSONObject) {
getAllXpathAndValueFromJsonObject((JSONObject) object, keyValueStore, keyPath);
}
if (object instanceof JSONArray) {
doJsonArray((JSONArray) object, keyPath, keyValueStore, json, key);
}
if (object instanceof String || object instanceof Boolean || object.equals(null)) {
String keyStr = "";
for (String keySub : keyPath) {
keyStr += keySub + ".";
}
keyStr = keyStr.substring(0, keyStr.length() - 1);
keyPath.pop();
keyValueStore.put(keyStr, json.get(key).toString());
}
}
if (keyPath.size() > 0) {
keyPath.pop();
}
return keyValueStore;
}
public void doJsonArray(JSONArray object, Stack<String> keyPath, Map<String, String> keyValueStore, JSONObject json,
String key) {
JSONArray arr = (JSONArray) object;
for (int i = 0; i < arr.length(); i++) {
keyPath.push(Integer.toString(i));
Object obj = arr.get(i);
if (obj instanceof JSONObject) {
getAllXpathAndValueFromJsonObject((JSONObject) obj, keyValueStore, keyPath);
}
if (obj instanceof JSONArray) {
doJsonArray((JSONArray) obj, keyPath, keyValueStore, json, key);
}
if (obj instanceof String || obj instanceof Boolean || obj.equals(null)) {
String keyStr = "";
for (String keySub : keyPath) {
keyStr += keySub + ".";
}
keyStr = keyStr.substring(0, keyStr.length() - 1);
keyPath.pop();
keyValueStore.put(keyStr , json.get(key).toString());
}
}
if (keyPath.size() > 0) {
keyPath.pop();
}
}