【问题标题】:add JSONArray within a JSONObject在 JSONObject 中添加 JSONArray
【发布时间】:2018-05-11 15:41:41
【问题描述】:

我正在制作一个使用 OneSignal 发送通知的应用程序,并且必须执行 JSON 格式的 POST 请求。

要向用户发送通知,我必须使用 include_player_ids 参数,该参数必须是一个数组,因为可以向多个用户发送相同的通知(在我的情况下,我只向一个用户发送通知)。 我使用 JSONArray 创建此数组,但将其添加到 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 是一个字符串

提前感谢您的帮助,

【问题讨论】:

  • notification.toString() 的结果在数组中有引号?另外,我认为您应该在添加到对象之前将 idUser 放在 player_id 中
  • @MarcosVasconcelos 是的 notification.toString() 有引号。这个顺序很奇怪,因为我正在关注一些这样做的教程。确实,将 idUser 放在前面更有意义。感谢回复

标签: java json onesignal


【解决方案1】:

我认为问题在于您使用的是org.json.alt.JSONArray 而不是org.json.JSONArray。我不熟悉那个类,但我怀疑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"]}

【讨论】:

    猜你喜欢
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    相关资源
    最近更新 更多