0
這裏需要一些邏輯的幫助 - 我試圖以特定的方式(父 - 子關係/樹格式)格式化數據到json中(我正在使用gson) 。但我似乎無法做到。下面是我能夠製作的最接近的格式,下面有我希望輸出的格式。這需要作爲散列表返回。如何將數據格式化爲特定的JSON格式
我遇到的一個問題是將[]括號放在「children」後面。在第一個「孩子」之後,括號就在那裏,但以後不會出現。我的猜測是因爲[]括號只在我使用HashSet時出現。那麼也許,將哈希集放入哈希集可以解決這個特殊問題?
我有它的代碼是在這裏:
public class DendrogramPlaySheet extends BrowserPlaySheet {
public Hashtable processQueryData() {
HashSet food = new HashSet();
String[] var = wrapper.getVariables();
for (int i=0; i<list.size(); i++){
LinkedHashMap foodType = new LinkedHashMap();
LinkedHashMap foodItem = new LinkedHashMap();
LinkedHashMap foodFlavor = new LinkedHashMap();
//this is a table of data that we get from a query
Object[] listElement = list.get(i);
//taking columns and putting them into the hashmap
foodType.put("name", listElement[0]);
foodItem.put("name", listElement[1]);
foodFlavor.put("name", listElement[2]);
foodItem.put("children", foodFlavor);
foodType.put("children", foodItem);
food.add(foodType);
}
Hashtable allHash = new Hashtable();
allHash.put("name", "Food");
allHash.put("children", food);
return allHash;
}
}
什麼我的代碼生成:
{
"name":"Food",
"children":[
{
"name":"Italian",
"children":{
"name":"Pizza",
"children":{
"name":"Cheese"
}
}
},
{
"name":"American",
"children":{
"name":"Hamburgers",
"children":{
"name":"Plain"
}
}
},
{
"name":"Italian",
"children":{
"name":"Pasta",
"children":{
"name":"Pesto"
}
}
},
{
"name":"Italian",
"children":{
"name":"Cannoli",
"children":{
"name":"Plain"
}
}
},
{
"name":"Italian",
"children":{
"name":"Pizza",
"children":{
"name":"Pepperoni"
}
}
},
{
"name":"Mexican",
"children":{
"name":"Burritos",
"children":{
"name":"Beef"
}
}
}
]
}
我想輸出:
{
"name":"Food",
"children":[
{
"name":"Italian",
"children":[
{
"name":"Pizza",
"children":[
{"name":"Pepperoni"},
{"name":"Cheese"},
]
},
{
"name":"Cannoli",
"children":[
{"name":"Plain"},
]
},
{
"name":"Pasta",
"children":[
{"name":"Pesto"},
]
},
]
},
{
"name":"American",
"children":[
{
"name":"Hamburgers",
"children":[
{"name":"Plain"},
]
},
]
},
{
"name":"Mexican",
"children":[
{
"name":"Burritos",
"children":[
{"name":"Beef"},
]
},
]
}
]
}