在 JSONObject 中添加 JSONArray

add JSONArray within a JSONObject

我正在申请使用 OneSignal 发送通知,并且必须以 JSON 格式执行 POST 请求。

要向用户发送通知,我必须使用 include_player_ids 参数,它必须是一个数组,因为可以向多个用户发送相同的通知(在我的例子中,我只向一个用户发送通知用户)。 我使用 JSON 数组来创建此数组,但将其添加到 JSONObject 时,字段 include_player_ids.

有额外的引号

我有:

{
  "headings": {"en":"my_title"},
  "contents": {"en":"my_text"},
  "include_player_ids": "[\"my-player-id\"]",
  "app_id":"my-app-id"
}

如您所见,数组 [ ] 周围有一些引号。

我想这是导致 OneSignal 响应错误的原因: errors":["include_player_ids must be an array"]

我想要什么:

...
"include_player_ids": ["my-player-id"] 
...

这很奇怪,因为将 JSONObject 添加到 JSONObject 不会执行此操作,即使它与标题 / 中看到的非常相似内容字段

我的代码:

import org.json.JSONException;
import org.json.JSONObject;
import org.json.alt.JSONArray;

JSONObject headings = new JSONObject();
JSONObject contents = new JSONObject();
JSONArray player_id = new JSONArray();
JSONObject notification = new JSONObject();
try {
    notification.put("app_id", appId);
    notification.put("include_player_ids", player_id);
    player_id.put(idUser);
    headings.put("en", "my_title");
    contents.put("en", "my_text");
    notification.put("headings", headings);
    notification.put("contents", contents);             

} catch (JSONException e) {
    System.out.println("JSONException :" + e.getMessage());
}

idUser 是一个字符串

在此先感谢您的帮助,

我认为问题在于您使用的是 org.json.alt.JSONArray 而不是 org.json.JSONArray。我不熟悉 class,但我怀疑 JSONObject.put 只是调用 toString() 而不是将其视为现有的 JSON 数组。这是一个简短但完整的示例, 没有问题:

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray; // Note the import here

public class Test {
    public static void main(String[] args) throws JSONException {
        JSONArray playerIds = new JSONArray();
        playerIds.put("a");
        playerIds.put("b");
        JSONObject notification = new JSONObject();
        notification.put("include_player_ids", playerIds);
        System.out.println(notification);
      }
}

输出:

{"include_player_ids":["a","b"]}