I am getting data in JSON format from FCM notification. It has different format based on notification types as below:
Format 1: accept_request:
{
"alert": "Accept Request By driver",
"title": "Accept Request By driver",
"booking_id": "247",
"notification_type": "accept_request"
}
Format 2: end_request:
{
"alert": "End trip By driver",
"title": "End trip By driver",
"booking_id": "247",
"notification_type": "end_request",
"servicesList": [
{
"service_id": "1",
"service_name": "Services1",
"status": "true",
"sub_category": [
{
"sub_cat_id": "1",
"sub_cat_name": "Doctors on call",
"service_cost": "15.00",
"service_cat_id": "1",
"cost": 0
}
],
"is_multiple_choose": "0",
"total_cost": 15
}
}
I have create CommonNotificationBean.java
as POJO class. I have successfully parsed data for accept_request
.
Its working because all key has String values and remoteMessage.getData()
also returning Map<String, String>
type values.
Code:
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData().get("notification_type"));
Map<String, String> params = remoteMessage.getData();
JSONObject object = new JSONObject(params);
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(object.toString()));
reader.setLenient(true);
CommonNotificationBean bean = gson.fromJson(reader, CommonNotificationBean.class);
sendNotification(bean);
}
PROBLEM:
Now I am stuck with problem while parsing end_request
data because it has Nested JSON Array.
Read it carefully:
What can I do for dynamic data instead of Map<String, String>
because it will not convert data into Map<String, String>
type as it has some List
type values.
Anyone can help?
It is simple, you should just have an abstract Notification object with the attributes
alert
,title
andnotification_type
. And then, have specific implementations based on your possible types, so far:AcceptRequestNotification extends Notification
with just an intbooking_id
(this is the one you already have, the one you called CommonNotificationBean)EndRequestNotification extends Notification
which contains for example, an ArrayList calledservicesList
, this ArrayList should be of typeService
and then, service would have the attributes:service_id
,service_name
,status
,sub_category
which is again another ArrayList of a custom type.And then you just change your code to be:
And finally I got solution by adding some drops of concepts. :)
I got many problems to converting in JSON with proper format like:
and Finally following code get worked for me.
Logcat:
remoteMessage.getData(): Getting data without double quotes.
new JSONObject(remoteMessage.getData()) : Converted to JSONObject but getting unwanted back slash and double quotes
Final JSON :
Full code : MyFirebaseMessagingService.java
Hope it will be help to others.