Directory listing to JSON using Java

115 views Asked by At

I need to have the below list of folders (directory listing) to be converted to JSON using Java:

"ListDirectories/"
"ListDirectories/folder1/"
"ListDirectories/folder1/folder3/"
"ListDirectories/folder2/"

And I want JSON as:

String data = "{text: 'ListDirectories',nodes:[{text:'folder1',nodes:[{text:'folder3'}]},{text:'folder2}]}";
2

There are 2 answers

2
segfault On BEST ANSWER

The way I would go about this would be to create a file system 'tree' by parsing the inputs and then converting this tree to a json.

A tree would have nodes as :

Node {
String name;
List<Node> children;
}

Try to form this tree when parsing the inputs. When a node is not there, create it in the tree.

Implement the toJSON(tree) by converting the tree to a JSON recursively.

0
Null-Pointer-Exception On

You can also refer to this. Here its solving using jquery , but similar approach can be taken to solve using java.