// Credits https://stackoverflow.com/questions/37848106/parse-json-object-recursively-javaimportorg.json.*;importjava.io.File;importjava.util.HashMap;importjava.util.Map;importcom.google.common.base.Charsets;importcom.google.common.io.Files;publicclasssolution{publicstaticfinalStringJSON_DATA_FILE_PATH="./data/source_37848106.json";privatestaticbooleanhasMoreFamilyName(JSONObjectjson){returnjson.has("familyMembers")&&json.get("familyMembers")!=JSONObject.NULL;}privatestaticvoidtrackFirstName(Map<String,Integer>nameTracker,JSONObjectjson){if(!nameTracker.containsKey(json.getString("firstName"))){nameTracker.put(json.getString("firstName"),/*DUMMY VALUE =*/1);}}privatestaticvoidgetNames(Map<String,Integer>nameTracker,JSONArrayjsonArr){for(inti=0;i<jsonArr.length();i++){JSONObjectitem=jsonArr.getJSONObject(i);if(hasMoreFamilyName(item)){getNames(nameTracker,item.getJSONArray("familyMembers"));}trackFirstName(nameTracker,item);}}publicstaticvoidmain(String[]args){Map<String,Integer>nameTracker=newHashMap<>();try{Stringtext=Files.toString(newFile(JSON_DATA_FILE_PATH),Charsets.UTF_8);JSONObjectjson=newJSONObject(text);getNames(nameTracker,json.getJSONArray("members"));}catch(Exceptionex){System.out.println("Something is wrong.");}for(Map.Entry<String,Integer>entry:nameTracker.entrySet()){System.out.println(entry.getKey());}}
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.