Java 从Hashmap中格式化JSON
我的问题是我有一个Hashmap来建立文件系统的层次结构。键是文件或文件夹的名称,以及层次结构中更深层次的文件的值哈希映射Java 从Hashmap中格式化JSON,java,json,gson,Java,Json,Gson,我的问题是我有一个Hashmap来建立文件系统的层次结构。键是文件或文件夹的名称,以及层次结构中更深层次的文件的值哈希映射 Hashmap ├── Key : Name of the File (eg. root) └── Value : Deeper Files ├── Hashmap File 1 │ ├── Key : Name of the File │ └── Value : Deeper Files └── Hashmap File 2
Hashmap
├── Key : Name of the File (eg. root)
└── Value : Deeper Files
├── Hashmap File 1
│ ├── Key : Name of the File
│ └── Value : Deeper Files
└── Hashmap File 2
├── ....
现在,我尝试将Gson的漂亮格式映射为JSON:
{
"": {
"src": {
"main": {
"java": {
"tools": {
"mockfile": {
"generator": {
"data": {
"RecordPart.java": {},
"RecordAll.java": {}
},
"AnalyzerTEST.java": {},
"AnalyzerSFTP.java": {}
}
...
但对于我的应用程序,我需要以下格式:
{
"name": "",
"children": [
{
"name": "src",
"children": [
{
"name": "main",
"children": [
{
"name": "tools",
"children": [
{
"name": "generator",
"children": [
{
"name": "data",
"children": [
{"name": "RecordTotal.java"},
{"name": "RecordAll.java"}
]
},
{"name": "AnalyzerTEST.java"},
{"name": "AnalyzerSFTP.java"}
]
}
...
有没有办法用我的Hashmap解决这个问题 假设我们有DTO
public class Data {
private String name;
private Data[] children;
public Data(String name, Data[] children) {
this.name = name;
this.children = children;
}
}
您需要将HashMap转换为DTO数据数组
以下是我们如何使用此方法:
HashMap<String, HashMap> map = // You already have that
Data[] data = convertMap2Data(map);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(data[0])); // If there is only one root use this
//System.out.println(gson.toJson(data)); // If there are multiple root
HashMap<String, HashMap> map = // You already have that
Data[] data = convertMap2Data(map);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(data[0])); // If there is only one root use this
//System.out.println(gson.toJson(data)); // If there are multiple root