【问题标题】:Parse a Bundle which is a JSONString in Remotemessage to JSON object将 Remotemessage 中的 JSONString Bundle 解析为 JSON 对象
【发布时间】:2018-05-16 05:51:53
【问题描述】:

我正在尝试解析 FCM 中的通知数据。我会尽可能详细地解释我的问题。我有两个应用程序一个是android,另一个是javascript webapp。所以当从 webapp 发送 pushnotification 到 androd 应用程序时,我以 jsonstring 格式发送通知数据。现在我无法将它转换为 java 端(android)上的 JSONObject。下面是我的代码

    var notification = {
    'TITLE': currentUser.displayName,
    'MSG': message,
    'CHAT_KEY': chatKey,
    'MSG_KEY': 'messageKey',
    'USER_DISPLAY_NAME': currentUser.displayName,
    'USER_EMAIL': currentUserEmail, 
    'USER_FCM_DEVICE_ID': toKey,
    'USER_FCM_DEVICE_ID_SENDER': fromKey,
  };

  fetch('https://fcm.googleapis.com/fcm/send', {
    'method': 'POST',
    'headers': {
      'Authorization': 'key=' + fromKey,
      'Content-Type': 'application/json'
    },
    'body': JSON.stringify({
      'notification': notification,
      'to': toKey
    })
  }).then(function(response) {
    console.log(response);
  }).catch(function(error) {
    console.error(error);
  })
};

在安卓端

@Override public void onMessageReceived(RemoteMessage remoteMessage) {

    if (remoteMessage.getNotification() != null) {


        sendDefaultNotification(remoteMessage.getNotification().getTitle(),
                remoteMessage.getNotification().getBody());
    } else {
        String currentUserEmail = "";
        FirebaseAuth auth = FirebaseAuth.getInstance();
        if (auth.getCurrentUser() != null && auth.getCurrentUser().getEmail() != null) {
            currentUserEmail = auth.getCurrentUser().getEmail();
        }

        String userName = remoteMessage.getData().get(Constants.KEY_USER_DISPLAY_NAME);
        String userEmail = remoteMessage.getData().get(Constants.KEY_USER_EMAIL);
        String chatKey = remoteMessage.getData().get(Constants.KEY_CHAT_KEY);
        String deviceId = remoteMessage.getData().get(Constants.KEY_USER_FCM_DEVICE_ID);
        String deviceIdSender = remoteMessage.getData().get(Constants.KEY_USER_FCM_DEVICE_ID_SENDER);
        String title = remoteMessage.getData().get(Constants.KEY_MSG_TITLE);
        String msg = remoteMessage.getData().get(Constants.KEY_MSG);
        String msgKey = remoteMessage.getData().get(Constants.KEY_MSG_KEY);

        /*if (chatKey.equals(ConstantsFirebase.FIREBASE_LOCATION_CHAT_GLOBAL)) {
            title = String.format("%s- %s", title, ConstantsFirebase.CHAT_GLOBAL_HELPER);
        } else {*/
            if (!currentUserEmail.equals(Utils.decodeEmail(userEmail))) {
                setMessageReceived(FirebaseDatabase.getInstance().getReference()
                        .child(ConstantsFirebase.FIREBASE_LOCATION_CHAT).child(chatKey).child(msgKey)
                        .child(ConstantsFirebase.FIREBASE_PROPERTY_MESSAGE_STATUS));
            }
      /*  }*/

        boolean notificationIsActive = PreferenceManager.getDefaultSharedPreferences(this)
                .getBoolean(Constants.KEY_PREF_NOTIFICATION, false);
        if (auth.getCurrentUser() != null && notificationIsActive) {
            if (!currentUserEmail.equals(Utils.decodeEmail(userEmail))) {

                Utils.setAdditionalData(new PushNotificationObject
                        .AdditionalData(title, msg, chatKey, msgKey, userName,
                        userEmail, deviceId, deviceIdSender));
                sendNotification(title, msg);
            }
        }
    }
}

在这里,我将 Remotemessage 直接视为 JSONObject,但它以捆绑 jsonstring 的形式出现。如何解析?

输出:

Bundle[{gcm.notification.USER_DISPLAY_NAME=ishku sukshi, google.sent_time=1512190657773, gcm.notification.TITLE=ishku sukshi, gcm.notification.USER_FCM_DEVICE_ID=fXLDo7zU7c0:APA91bFx0sIGwIZ9jIm7xi7QvSrWKrL29uWJnNT0jujlyVHTScUteuRZ37nB-FgEeBXokZdQfmyGKhhRLjCILraS8sTif4p6DRJ_jZkNlh-J_yhKTAU3WnBYzGBtlaTorcAJhDtd1AIy, gcm.notification.CHAT_KEY=-L-FVx8eZBuz-QIsnXvx, from=1028795933953, gcm.notification.USER_EMAIL=ishkumihu@gmail,com, google.message_id=0:1512190657780774%bfd1fc79bfd1fc79, gcm.notification.MSG_KEY=messageKey, gcm.notification.MSG=, gcm.notification.USER_FCM_DEVICE_ID_SENDER=AAAA74kEJQE:APA91bHN5lJf0S8KNXzhU4XL1rz1rqyZ6ziY4UghZudtW6iH84ytQksWMSvSKsaBqQEsw7P2txk-yTGp5DOYElb7pdg8VFgj8wecJUcsPKJ6JCASCO_ihXh6xpo3a2aDuw8HnHPvL0Mr, collapse_key=com.sukshi.sukshichat}]

实际上 gcm.notification 附加每个键也不应该出现,我不知道为什么会这样。

【问题讨论】:

  • 你得到的错误是什么?您想将远程消息转换为 JSONObject 吗?你其实不需要这个,在这种情况下你也可以获取JSON的值?
  • 但是我得到的数据是 JSONSTRING 格式的。如何从 jsonstring 中获取 json 的值?
  • 您需要拥有 JSON 或者您只需要这些值。 String userName = data.get(Constants.KEY_USER_DISPLAY_NAME.name()).toString()这可能对你有用吗?
  • 我需要 json
  • 请打印 remoteMessge#getData() 并将输出添加到问题中,以便我们查看您收到的数据类型。如果是 json 字符串,可以使用 JSONObject jsonObj = new JSONObject(jsonStr); 将其转换为 JSON Object

标签: javascript java android json stringify


【解决方案1】:

实际上,您是从 RemoteMessage#getData() 方法获取 Map 对象。 因此,如果您需要一个 json 对象,您可以自己创建它,如下所示

JSONObject json = new JSONObject();
//data is RemoteMessage#getData();
Set<String> keys = data.keySet();
for (String key : keys) {
    try {
       json.put(key, JSONObject.wrap(data.get(key)));
    } catch(JSONException e) {
        //Handle exception here
  }
}

【讨论】:

  • 如果确实解决了您的问题,请采纳。
  • 通过使用这个我得到 keys = 0 我在图片中添加我的输出图片。
【解决方案2】:

尝试从 json 的字符串表示中生成JSONObject。在服务器端代码上将 notification 更改为 data。喜欢 -

fetch('https://fcm.googleapis.com/fcm/send', {
    'method': 'POST',
    'headers': {
      'Authorization': 'key=' + fromKey,
      'Content-Type': 'application/json'
    },
    'body': JSON.stringify({
      'data': notification,
      'to': toKey
    })
  }).then(function(response) {
    console.log(response);
  }).catch(function(error) {
    console.error(error);
  })
};

并在 Android 端获取您的 fcm 消息 -

String body = remoteMessage.getData();
JSONObject json = new JSONObject(body );
Log.d("json", json.toString());

然后您可以通过从 javascript 分配的键获取值。喜欢-json.get("USER_DISPLAY_NAME");

告诉我进展如何。

【讨论】:

  • 尝试在空对象引用上调用虚拟方法'java.lang.String com.google.firebase.messaging.RemoteMessage$Notification.getBody()' 如果我实现,这是我得到的错误你的方式。
  • 你能发布remoteMessage.getNotification()toString() 的内容吗?
  • 可以与您联系吗?喜欢在 Skype 或视频群聊中?过去 3 天我一直在努力解决这个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-27
  • 2014-10-17
  • 1970-01-01
相关资源
最近更新 更多