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
I made a small recursive function that goes through the entire json object and saves the key path and its value.
// My stored keys and values from the json object
HashMap myKeyValues = new HashMap();
// Used for constructing the path to the key in the json object
Stack key_path = new Stack();
// Recursive function that goes through a json object and stores
// its key and values in the hashmap
private void loadJson(JSONObject json){
Iterator> json_keys = json.keys();
while( json_keys.hasNext() ){
String json_key = (String)json_keys.next();
try{
key_path.push(json_key);
loadJson(json.getJSONObject(json_key));
}catch (JSONException e){
// Build the path to the key
String key = "";
for(String sub_key: key_path){
key += sub_key+".";
}
key = key.substring(0,key.length()-1);
System.out.println(key+": "+json.getString(json_key));
key_path.pop();
myKeyValues.put(key, json.getString(json_key));
}
}
if(key_path.size() > 0){
key_path.pop();
}
}