最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Parse a Bundle which is a JSONString in Remotemessage to JSON object - Stack Overflow

programmeradmin4浏览0评论

I am trying to parse the notification data in FCM. I will try to explain my problem as detailed as i can. I have to two apps one is android and the other is javascript webapp. so when sending pushnotification from webapp to androd app I am sending the notification data in jsonstring format. Now i am unable to convert it to JSONObject on the java side(android). Below is my code

    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('', {
    '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);
  })
};

And on the android side

@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);
            }
        }
    }
}

Here I am considering the Remotemessage directly as JSONObject but it's ing in bundle jsonstring. How do I parse it?

Output:

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,, 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=.sukshi.sukshichat}]

Actually gcm.notification appending each key also should not e , I don't know why that's ing.

I am trying to parse the notification data in FCM. I will try to explain my problem as detailed as i can. I have to two apps one is android and the other is javascript webapp. so when sending pushnotification from webapp to androd app I am sending the notification data in jsonstring format. Now i am unable to convert it to JSONObject on the java side(android). Below is my code

    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./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);
  })
};

And on the android side

@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);
            }
        }
    }
}

Here I am considering the Remotemessage directly as JSONObject but it's ing in bundle jsonstring. How do I parse it?

Output:

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,, 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=.sukshi.sukshichat}]

Actually gcm.notification appending each key also should not e , I don't know why that's ing.

Share Improve this question edited Jan 18, 2018 at 18:41 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked Dec 2, 2017 at 5:40 Stackover67Stackover67 3572 gold badges4 silver badges18 bronze badges 6
  • What is the error you get? You want to convert your remote message into JSONObject? You actually don't need this, you can get the value of JSON in this case also? – Oguz Ozcan Commented Dec 2, 2017 at 6:03
  • But the data I ma getting is in JSONSTRING format. How can i get values of json from jsonstring? – Stackover67 Commented Dec 2, 2017 at 6:05
  • You need to have the JSON or you only need the values. String userName = data.get(Constants.KEY_USER_DISPLAY_NAME.name()).toString() this might work for you? – Oguz Ozcan Commented Dec 2, 2017 at 6:07
  • I need to have the json – Stackover67 Commented Dec 2, 2017 at 6:11
  • Please print remoteMessge#getData() and add output to question, so that we can see what type of data you're receiving. If it's a json string, you can convert it into JSON Object by using : JSONObject jsonObj = new JSONObject(jsonStr); – dpaksoni Commented Dec 2, 2017 at 6:24
 |  Show 1 more ment

2 Answers 2

Reset to default 3

Actually you're getting Map object from RemoteMessage#getData() method. So if you need a json object, what you can do is create it on your own like below

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
  }
}

Try with making JSONObject from string representation of json. Change you notification to data on server side code. Like -

fetch('https://fcm.googleapis./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);
  })
};

And get your fcm message on Android side -

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

Then you can get value by key assigned from javascript. Like - json.get("USER_DISPLAY_NAME");

And let me know how its going.

发布评论

评论列表(0)

  1. 暂无评论