我试图弄清楚如何将以下数据添加到我的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<JSONObject> items = new ArrayList<JSONObject>(); 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());