-
-
Save sapanparikh18/5365ec4d5a3d82b7c2f9489af34d7840 to your computer and use it in GitHub Desktop.
Java representation of directory structure. Need help on rewriting buildJson function. It should return JSON compatible with D3's circle packing data source.
And mainly it should work :-|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package codesnapper; | |
import com.google.gson.Gson; | |
import com.google.gson.JsonArray; | |
import com.google.gson.JsonObject; | |
import java.util.HashMap; | |
import java.util.Map; | |
public class Dir { | |
private Map<String, Dir> dirs = new HashMap<>(); | |
private Map<String, GitFile> files = new HashMap<>(); | |
private String name; | |
public Dir(String name){ | |
this.name = name; | |
} | |
public String getName() { | |
return name; | |
} | |
public void addFile(GitFile gitFile) { | |
String[] folders = gitFile.getPath().split("/"); | |
Dir leafNode = this; | |
for (String folder : folders) { | |
if (!folder.isEmpty()) { | |
if (leafNode.dirs.containsKey(folder)) { | |
leafNode = leafNode.dirs.get(folder); | |
} else { | |
Dir newLeaf = new Dir(folder); | |
leafNode.dirs.put(folder, newLeaf); | |
leafNode = newLeaf; | |
} | |
} | |
} | |
leafNode.files.put(gitFile.getName(), gitFile); | |
System.out.println(new Gson().toJson(this) ); | |
} | |
public Dir get(String path) { | |
Dir dir = this; | |
String[] folders = path.split("/"); | |
for (String folder : folders) { | |
if (!folder.isEmpty()) { | |
dir = dir.dirs.get(folder); | |
} | |
} | |
return dir; | |
} | |
public JsonObject toJson(){ | |
JsonObject object = new JsonObject(); | |
// buildJson(object); | |
//System.out.println(object); | |
return buildJson(object); | |
} | |
private JsonObject buildJson(JsonObject object){ | |
System.out.println("generating json for "+this.name); | |
for(Map.Entry<String,Dir> entry:dirs.entrySet()){ | |
Dir thisDir = entry.getValue(); | |
object.addProperty("name",thisDir.name); | |
JsonArray element = (JsonArray) new Gson().toJsonTree( thisDir.files.values()); | |
element.add(thisDir.toJson()); | |
object.add("children",element); | |
} | |
System.out.println(object); | |
return object; | |
} | |
@Override | |
public String toString() { | |
return "Dir{" + | |
"dirs=" + dirs + | |
", files=" + files + | |
'}'; | |
} | |
public GitFile getGitFile(String name) { | |
return this.files.get(name); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment