Java中JSON嵌套数据创建失败
我得到的结果是Java中JSON嵌套数据创建失败,java,json,json-lib,Java,Json,Json Lib,我得到的结果是 import net.sf.json.*; public class JSONDemo { /** * @param args */ public static void main(String[] args) { JSONObject mainObj = new JSONObject(); JSONObject jObj1 = new JSONObject(); JSONObject jObj2 = new JSONObject();
import net.sf.json.*;
public class JSONDemo {
/**
* @param args
*/
public static void main(String[] args) {
JSONObject mainObj = new JSONObject();
JSONObject jObj1 = new JSONObject();
JSONObject jObj2 = new JSONObject();
JSONArray jA1 = new JSONArray();
JSONArray jA2 = new JSONArray();
JSONArray mainArray= new JSONArray();
jObj1.accumulate("id", 17);
jObj1.accumulate("name", "Alex");
jObj1.accumulate("children", jA1);
mainArray.add(jObj1);
jObj2.accumulate("id", 94);
jObj2.accumulate("name", "Steve");
jObj2.accumulate("children", jA2);
//Adding the new object to jObj1 via jA1
jA1.add(jObj2);
mainObj.accumulate("ccgs", mainArray);
System.out.println(mainObj.toString());
}
}
我想要
jObj2
在jObj1的children键中
然后你可以这样做
{"ccgs":[{"id":17,"name":"Alex","children":[]}]}
显然,节点创建顺序对生成的字符串有影响。如果更改对象创建顺序(从子对象开始),则Json是正确的
请参阅该代码:
JSONObject mainObj = new JSONObject();
JSONObject jObj1 = new JSONObject();
JSONObject jObj2 = new JSONObject();
JSONArray jA1 = new JSONArray();
JSONArray jA2 = new JSONArray();
JSONArray mainArray= new JSONArray();
jObj2.accumulate("id", 94);
jObj2.accumulate("name", "Steve");
jObj2.accumulate("children", jA2);
jObj1.accumulate("id", 17);
jObj1.accumulate("name", "Alex");
jObj1.accumulate("children", jObj2);
mainArray.add(jObj1);
//Adding the new object to jObj1 via jA1
jA1.add(jObj2);
mainObj.accumulate("ccgs", mainArray);
System.out.println(mainObj.toString());
输出为:
public static void main(String[] args) {
// first create the child node
JSONObject jObj2 = new JSONObject();
jObj2.accumulate("id", 94);
jObj2.accumulate("name", "Steve");
jObj2.accumulate("children", new JSONArray());
// then create the parent's children array
JSONArray jA1 = new JSONArray();
jA1.add(jObj2);
// then create the parent
JSONObject jObj1 = new JSONObject();
jObj1.accumulate("id", 17);
jObj1.accumulate("name", "Alex");
jObj1.accumulate("children", jA1);
// then create the main array
JSONArray mainArray = new JSONArray();
mainArray.add(jObj1);
// then create the main object
JSONObject mainObj = new JSONObject();
mainObj.accumulate("ccgs", mainArray);
System.out.println(mainObj);
}
但是如果我想用Alex的children键再添加一个Steve的兄弟姐妹呢?那么您必须添加数组中的所有兄弟姐妹,并将数组添加到children节点。
{"ccgs":[{"id":17,"name":"Alex","children":[{"id":94,"name":"Steve","children":[]}]}]}