我正在尝试从文件夹结构生成json表示。
示例文件夹/文件结构:
folder
|_ meta.xml
|_ subdir1
|_ textfile1.txt
|_ subdir2
|_ textfile2.txt
手动生成此结构的json表示:
def builder = new net.sf.json.groovy.JsonGroovyBuilder()
def json = builder.dir {
file(name: "meta.xml")
folder(name: "subdir1") {
file(name: "textfile.txt")
}
folder(name: "subdir2") {
file(name: "textfile3.txt")
}
}
产生
{
"dir":{
"file":{
"name":"meta.xml"
},
"folder":[
{
"name":"subdir1"
},
{
"file":[
{
"name":"textfile.txt"
}
]
},
[
{
"name":"subdir2"
},
{
"file":[
{
"name":"textfile3.txt"
}
]
}
]
]
}
}
以文件夹结构的Groovy方式:
new File("./dir" ).eachFileRecurse{file ->
println file
}
产生
.\dir\meta.xml
.\dir\subdir1
.\dir\subdir1\textfile1.txt
.\dir\subdir2
.\dir\subdir2\textfile2.txt
但如何将这些放在一起自动生成?
答案 0 :(得分:0)
def paths = [:]
def listOfPaths = []
def access = {d, path ->
if (d[path] == null) {
d[path] = [:]
}
return d[path]
}
new File('./dir').eachFileRecurse{ file ->
listOfPaths << file.toString().tokenize('/')
}
listOfPaths.each{ path ->
def currentPath = paths
path.each { step ->
currentPath = access(currentPath, step)
}
}
所以剩下要做的就是将paths
转换为JSON。
希望它有所帮助!