Parse Nested JSON Array from Notification Data using Gson in Android

前端 未结 2 1466
醉话见心
醉话见心 2021-01-16 23:55

I am getting data in JSON format from FCM notification. It has different format based on notification types as below:

Format 1: accept_request:

2条回答
  •  死守一世寂寞
    2021-01-17 00:11

    It is simple, you should just have an abstract Notification object with the attributes alert, title and notification_type. And then, have specific implementations based on your possible types, so far:

    • AcceptRequestNotification extends Notification with just an int booking_id (this is the one you already have, the one you called CommonNotificationBean)
    • EndRequestNotification extends Notification which contains for example, an ArrayList called servicesList, this ArrayList should be of type Service 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:

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData().get("notification_type"));
        Map params = remoteMessage.getData();
    
        JSONObject object = new JSONObject(params);
    
        Gson gson = new Gson();
        JsonReader reader = new JsonReader(new StringReader(object.toString()));
        reader.setLenient(true);
    
        Class typeOf;
    
        switch(remoteMessage.getData().get("notification_type")) {
            case "accept_request":
                typeOf = AcceptRequestNotification.class;
            break;
            case "end_request":
                typeOf = EndRequestNotification.class;
            break;
        }
    
        //you can cast this object later on (to the corresponding custom subclass of Notification), based on the notif.getNotificationType() value.
        Notification notif = gson.fromJson(reader, typeOf);
    
        sendNotification(notif);
    }
    

提交回复
热议问题