1
在我的PHP的服務器我傳遞應該是什麼編碼的JSONObject到PubNub通道爲:處理字符串傳遞到JSONObject的
$post_data = array("type"=> "groupMessage", "data" => array("chatUser" => "SERVER", "chatMsg" => "Now lets talk", "chatTime"=>1446514201516));
$post_data = json_encode($post_data, JSON_FORCE_OBJECT);
$info = $pubnub->publish('MainChat', $post_data);
請注意,我用的JSON_FORCE_OBJECT
,應保證的JSONObject的輸出。引用日誌,則輸出如:
{"type":"groupMessage","data":{"chatUser":"SERVER","chatMsg":"Now lets talk","chatTime":1446514201516}}
但是,客戶端Android應用內,測試的類傳入消息的信道上返回,這是一個字符串對象,而不是JSON,並且不會獲得通過if (message instanceof JSONObject) {
:
Log.d("message class", message.getClass().toString());
if (message instanceof JSONObject) {
try {
JSONObject jsonObj = (JSONObject) message;
Log.d("jsonObj is ", jsonObj.toString());
JSONObject json = jsonObj.getJSONObject("data");
final String name = json.getString(Constants.JSON_USER);
Log.d("name is: ", name);
final String msg = json.getString(Constants.JSON_MSG);
Log.d("msg is: ", msg);
final long time = json.getLong(Constants.JSON_TIME);
Log.d("time is: ", String.valueOf(time));
if (name.equals(mPubNub.getUUID())) return; // Ignore own messages
final ChatMessage chatMsg = new ChatMessage(name, msg, time);
presentActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
// Adding messages published to the channel
mChatAdapter.addMessage(chatMsg);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
如何確保PHP將JSONObject傳遞到通道中?
設備上的響應(消息)仍然只是一個字符串。你需要將它轉換爲JSONObject jsonObj =新的JSONObject(消息),使其成爲JSONObject的實例 – mjp66
@Sauron - 這不是一個重複問題,你問這裏 http://stackoverflow.com/questions/33490282/ pubnub服務器 - 不 - 不格式消息正確 –