【发布时间】: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 放在前面更有意义。感谢回复