将数据添加到JSONObject

我正在试图找出如何将以下数据添加到我的json对象。 有人可以告诉我如何做到这一点。

网站示例

$(document).ready(function() { $('#example').dataTable( { "aoColumnDefs": [ { "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] }, { "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] }, { "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] } ] } ); } ); 

我的JSONObject需要包含上面的例子。

  JSONObject json = new JSONObject(); json.put("aoColumnDefs", ); 

为了得到这个结果:

 {"aoColumnDefs":[{"aTargets":[0],"aDataSort":[0,1]},{"aTargets":[1],"aDataSort":[1,0]},{"aTargets":[2],"aDataSort":[2,3,4]}]} 

保存相同的数据:

  { "aoColumnDefs": [ { "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] }, { "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] }, { "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] } ] } 

你可以使用这段代码:

  JSONObject jo = new JSONObject(); Collection items = new ArrayList(); JSONObject item1 = new JSONObject(); item1.put("aDataSort", new JSONArray(0, 1)); item1.put("aTargets", new JSONArray(0)); items.add(item1); JSONObject item2 = new JSONObject(); item2.put("aDataSort", new JSONArray(1, 0)); item2.put("aTargets", new JSONArray(1)); items.add(item2); JSONObject item3 = new JSONObject(); item3.put("aDataSort", new JSONArray(2, 3, 4)); item3.put("aTargets", new JSONArray(2)); items.add(item3); jo.put("aoColumnDefs", new JSONArray(items)); System.out.println(jo.toString()); 

答案是使用JSONArray ,并“深入”潜入树结构:

 JSONArray arr = new JSONArray(); arr.put (...); // a new JSONObject() arr.put (...); // a new JSONObject() JSONObject json = new JSONObject(); json.put ("aoColumnDefs",arr); 

Francisco Spaeth接受的答案很有效,很容易理解。 但是,我认为构建JSON的方法很糟糕! 这对我来说真的很有用,因为我将一些Python转换为Java,我可以使用字典和嵌套列表等来轻松地构建JSON。

我真正不喜欢的是必须实例化单独的对象(通常甚至命名它们)来构建这些嵌套。 如果你有很多对象或数据需要处理,或者你的使用更抽象,那真的很痛苦!

我试图通过尝试清除和重用临时json对象和列表来解决其中一些问题,但这对我不起作用,因为这些Java对象中的所有put和gets等都是通过引用而不是值进行工作。 所以,在最后仍然有一些丑陋的(虽然风格不同)代码后,我最终会得到包含一堆棘手数据的JSON对象。

所以,这就是我提出要清理它的方法。 它可以使用进一步的开发,但这应该有助于作为寻找更合理的JSON构建代码的人的基础:

 import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.List; import org.json.simple.JSONObject; // create and initialize an object public static JSONObject buildObject( final SimpleEntry... entries ) { JSONObject object = new JSONObject(); for( SimpleEntry e : entries ) object.put( e.getKey(), e.getValue() ); return object; } // nest a list of objects inside another public static void putObjects( final JSONObject parentObject, final String key, final JSONObject... objects ) { List objectList = new ArrayList(); for( JSONObject o : objects ) objectList.add( o ); parentObject.put( key, objectList ); } 

实施示例:

 JSONObject jsonRequest = new JSONObject(); putObjects( jsonRequest, "parent1Key", buildObject( new SimpleEntry( "child1Key1", "someValue" ) , new SimpleEntry( "child1Key2", "someValue" ) ) , buildObject( new SimpleEntry( "child2Key1", "someValue" ) , new SimpleEntry( "child2Key2", "someValue" ) ) );