我需要生成这个JSON对象
{
"Soft Drinks": {
"T2": [
{
"name": "Bottled",
"T3": [
{
"name": "Lemon",
"T4": [
{
"leaf": [
{
"name": "500 ML"
}
]
}
]
}
]
}
]
}
}
但我总是以这个JSON
结束{
"Soft Drinks": {
"T2": [
{
"name": "Bottled",
"T3": [
{
"name": "Lemon",
"leaf": [
{
"name": "500 ML"
}
]
}
]
}
]
}
}
叶级对象应该属于不同的对象,即T4
这是我的程序
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class BuildJSOn {
public static void main(String[] args) throws JSONException {
JSONObject leaf = new JSONObject().put("name", "500 ML");
JSONObject lemon = new JSONObject().put("name", "Lemon").put("leaf", new JSONArray().put(leaf));
JSONArray t3Array = new JSONArray().put(lemon);
JSONObject bottled = new JSONObject().put("name", "Bottled").put("T3", t3Array);
JSONObject softDrink = new JSONObject().put("T2", new JSONArray().put(bottled));
JSONObject json = new JSONObject().put("Soft Drinks", softDrink);
System.out.println(json);
}
}
答案 0 :(得分:2)
试试这个:
JSONArray t4Array= new JSONArray();
JSONArray leaf= new JSONArray();
JSONObject newLeaf = new JSONObject().put("name", "500 ML");
leaf.put(newLeaf);
JSONObject t4Obj= new JSONObject().put("leaf",leaf);
t4Array.put(t4Obj);
JSONObject lemon = new JSONObject().put("name", "Lemon").put("T4", t4Array);
JSONArray t3Array = new JSONArray().put(lemon);
JSONObject bottled = new JSONObject().put("name", "Bottled").put("T3", t3Array);
JSONObject softDrink = new JSONObject().put("T2", new JSONArray().put(bottled));
JSONObject json = new JSONObject().put("Soft Drinks", softDrink);
希望它有所帮助。
答案 1 :(得分:1)
根据您需要的JSON结构,这就是您的代码的外观。
JSONObject lemon = new JSONObject().put("name", "Lemon");
JSONArray t4 = new JSONArray().put(new JSONObject().put("leaf", new JSONArray().put(leaf)));
lemon.put("T4", t4);
答案 2 :(得分:0)
你似乎没有在任何地方提到T4。你没有说明你正在使用的库,或者你正在使用的库是如何工作的(我假设如果你不知道如何向其中添加数组,你自己就不写它)但我猜你是需要像你在添加早期数组时所做的那样:
JSONArray t3Array = new JSONArray().put(lemon).put("T4", new JSONArray().put(leaf));
这并不是一个特别好的解决方案,而且数据结构看起来有点奇怪,但你需要在某处添加JSONArray
T4!