2010-05-27 89 views
2

我试图从文件夹结构生成json表示。从文件夹结构构建json,反之亦然

Examplee文件夹/文件结构:

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
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。

希望它有帮助!