views:

25

answers:

0

Hi, I'm trying to generate a json representation from a folder structure.

Examplee folder/file structure:

folder
|_ meta.xml
|_ subdir1
   |_ textfile1.txt
|_ subdir2
   |_ textfile2.txt 

Manually generate the json representation of this structure:

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")
    }
}

generates:

{
   "dir":{
      "file":{
         "name":"meta.xml"
      },
      "folder":[
         {
            "name":"subdir1"
         },
         {
            "file":[
               {
                  "name":"textfile.txt"
               }
            ]
         },
         [
            {
               "name":"subdir2"
            },
            {
               "file":[
                  {
                     "name":"textfile3.txt"
                  }
               ]
            }
         ]
      ]
   }
}

Groovy way of walking the folder structure:

new File("./dir" ).eachFileRecurse{file ->
    println file
}

generates:

.\dir\meta.xml
.\dir\subdir1
.\dir\subdir1\textfile1.txt
.\dir\subdir2
.\dir\subdir2\textfile2.txt

But how to put these together to generate this automatically?