I use a JSON library called JSONObject
(I don\'t mind switching if I need to).
I know how to iterate over JSONArrays
, but when I parse JSO
This is is another working solution to the problem:
public void test (){
Map keyValueStore = new HasMap<>();
Stack keyPath = new Stack();
JSONObject json = new JSONObject("thisYourJsonObject");
keyValueStore = getAllXpathAndValueFromJsonObject(json, keyValueStore, keyPath);
for(Map.Entry map : keyValueStore.entrySet()) {
System.out.println(map.getKey() + ":" + map.getValue());
}
}
public Map getAllXpathAndValueFromJsonObject(JSONObject json, Map keyValueStore, Stack keyPath) {
Set 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 keyPath, Map 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();
}
}