Vic*_*son 5 java json onesignal
我正在创建一个使用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"
}
Run Code Online (Sandbox Code Playgroud)
如您所见,数组[]周围有一些引用.
我猜这是OneSignal的响应错误:
errors":["include_player_ids must be an array"]
我想要的是 :
...
"include_player_ids": ["my-player-id"]
...
Run Code Online (Sandbox Code Playgroud)
这很奇怪,因为将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());
}
Run Code Online (Sandbox Code Playgroud)
idUser 是一个字符串
在此先感谢您的帮助,
Jon*_*eet 10
我相信问题是你用的是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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
{"include_player_ids":["a","b"]}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3877 次 |
| 最近记录: |