向JSON对象添加空数组

9

我正在尝试创建一个类似下面的 JSON 对象:

{"filters": {"defaultOperator":"OR", "filters":[]}}

我应该向我的 JSON 对象中添加什么才能使其成为空数组对象?我想不出空数组的具体写法。

我已经尝试过 jo1.put("filters",new Object[0]);,但这样并不起作用。

我正在测试一个需要在特定情况下填充数组的 API,大部分时间它都是空的。但不知道该如何添加它。我正在创建入口 JSON 如下:

JSONObject jo1 = new JSONObject();
                 jo1.put("defaultOperator", "OR");
                 jo1.put("filters","[]");

                 jo3 = new JSONObject();
                 jo3.put("filters", jo1);

                 //Toast.makeText(getApplicationContext(),""+jo3.toString() , Toast.LENGTH_LONG).show();


                 //json = new GsonBuilder().create().toJson(comment1, Map.class);
                 httppost.setEntity(new StringEntity(jo3.toString()));
1个回答

25
 JSONArray jarr = new JSONArray();
 jo1.put("filters",jarr);

或者全部放在一行上:

jo1.put("filters", new JSONArray());

1
完美,有时简单的答案可以奇迹般地帮助代码。非常感谢。接受了这个答案。 - anil keshav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接