How to parse Json data in android for Firebase Cloud Messaging (FCM)

try this code:

public void onMessageReceived(RemoteMessage remoteMessage)
    {
        Log.e("DATA",remoteMessage.getData().toString());
        try
        {
            Map<String, String> params = remoteMessage.getData();
            JSONObject object = new JSONObject(params);
            Log.e("JSON OBJECT", object.toString());
            String callNumber = object.getString("callNumber");
            //rest of the code
      }
   }

Also make sure your JSON is valid use This


I have changed to

JSONObject json = new JSONObject(remoteMessage.getData());

from

JSONObject json = new JSONObject(remoteMessage.getData().toString());

and work fine.


Faced this issue when migrating from GCM to FCM.

The following is working for my use case (and OP payload), so perhaps it will work for others.

JsonObject jsonObject = new JsonObject(); // com.google.gson.JsonObject
JsonParser jsonParser = new JsonParser(); // com.google.gson.JsonParser
Map<String, String> map = remoteMessage.getData();
String val;

for (String key : map.keySet()) {
    val = map.get(key);
    try {
        jsonObject.add(key, jsonParser.parse(val));
    } catch (Exception e) {
        jsonObject.addProperty(key, val);
    }
}

// Now you can traverse jsonObject, or use to populate a custom object:
// MyObj o = new Gson().fromJson(jsonObject, MyObj.class)