Разбор вложенного массива JSON из данных уведомлений с использованием Gson в Android - PullRequest
0 голосов
/ 29 марта 2019

Я получаю данные в формате JSON из уведомления FCM. Он имеет другой формат в зависимости от типа уведомления, как показано ниже:

Формат 1: принять запрос:

{
   "alert": "Accept Request By driver",
   "title": "Accept Request By driver",
   "booking_id": "247",
   "notification_type": "accept_request"
}

Формат 2: конечный запрос:

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

Я создал CommonNotificationBean.java как класс POJO. Я успешно проанализировал данные для accept_request.

Это работает, потому что все ключи имеют строковые значения и remoteMessage.getData() также возвращают значения типа Map<String, String>.

Код:

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

ПРОБЛЕМА:

Теперь я застрял с проблемой при разборе end_request данных, потому что у них есть вложенный массив JSON.

Внимательно прочитайте:

Что я могу сделать для динамических данных вместо Map<String, String>, потому что они не будут преобразовывать данные в тип Map<String, String>, так как имеют некоторые значения типа List.

Кто-нибудь может помочь?

Ответы [ 2 ]

1 голос
/ 30 марта 2019

И, наконец, я нашел решение, добавив несколько понятий. :)

У меня много проблем с преобразованием в JSON с правильным форматом, таким как:

  • Неопределенный объект на символе
  • MalformedJsonException

и, наконец, следующий код работает для меня.

  if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "remoteMessage.getData() : " + remoteMessage.getData());

        // Map<String, String> stringStringMap = remoteMessage.getData();

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

        Log.d(TAG, "new JSONObject(remoteMessage.getData()) : " + object.toString());

        String finalJSON = object.toString().replaceAll("\\\\", "").replace("\"[", "[").replace("]\"", "]");

        Log.d(TAG, "Replace all back slash and invalid double quotes : " + finalJSON);

        CommonNotificationBean bean = new Gson().fromJson(finalJSON, CommonNotificationBean.class);

        sendNotification(bean);
    }

Logcat:

remoteMessage.getData (): Получение данных без двойных кавычек.

remoteMessage.getData() : {content-available=1, notification_type=end_request, booking_id=247, priority=high, base_price=35, totalMinutePrice=1.5, alert=End trip By driver, sound=default, title=End trip By driver, total_amount=397, address_from=A/ 4 forum bungalow Nr. Hicort, Sola, Ahmedabad, Gujarat 380015, India, service_cost=360, servicesList=[{"total_cost":15,"sub_category":[{"cost":0,"sub_cat_name":"Doctors on call","sub_cat_id":"1","service_cost":"15.00","service_cat_id":"1"}],"service_name":"Services1","service_id":"1","is_multiple_choose":"0","status":"true"},{"total_cost":95,"sub_category":[{"cost":0,"sub_cat_name":"Hand","sub_cat_id":"3","service_cost":"20.00","service_cat_id":"2"},{"cost":0,"sub_cat_name":"Body","sub_cat_id":"4","service_cost":"75.00","service_cat_id":"2"}],"service_name":"Dressing","service_id":"2","is_multiple_choose":"1","status":"true"},{"total_cost":0,"sub_category":[{"cost":0,"sub_cat_name":"No","sub_cat_id":"7","service_cost":"0.00","service_cat_id":"3"}],"service_name":"Do you need oxygen?","service_id":"3","is_multiple_choose":"0","status":"true"},{"total_cost":30,"sub_category":[{"cost":0,"sub_cat_name":"Level 3","sub_cat_id":"10","service_cost":"30.00","service_cat_id":"4"}],"service_name":"Lift\/Stairs Accessibility","service_id":"4","is_multiple_choose":"0","status":"true"},{"total_cost":220,"sub_category":[{"cost":0,"sub_cat_name":"Ventilator","sub_cat_id":"12","service_cost":"100.00","service_cat_id":"5"},{"cost":0,"sub_cat_name":"Intracenous (IV) drip","sub_cat_id":"13","service_cost":"120.00","service_cat_id":"5"}],"service_name":"Other Medical","service_id":"5","is_multiple_choose":"1","status":"true"},{}], tripdatetime=2019-03-27 10:57:51, address_to=19/20, Chanakyapuri, Ahmedabad, Gujarat 382481, India, notification_date_time=28-03-2019 17:24:09}

новый JSONObject (remoteMessage.getData ()): Преобразован в JSONObject, но получает нежелательный слеш и двойные кавычки

new JSONObject(remoteMessage.getData()) : {"content-available":"1","notification_type":"end_request","booking_id":"247","priority":"high","base_price":"35","totalMinutePrice":"1.5","alert":"End trip By driver","sound":"default","title":"End trip By driver","total_amount":"397","address_from":"A\/ 4 forum bungalow Nr. Hicort, Sola, Ahmedabad, Gujarat 380015, India","service_cost":"360","servicesList":"[{\"total_cost\":15,\"sub_category\":[{\"cost\":0,\"sub_cat_name\":\"Doctors on call\",\"sub_cat_id\":\"1\",\"service_cost\":\"15.00\",\"service_cat_id\":\"1\"}],\"service_name\":\"Services1\",\"service_id\":\"1\",\"is_multiple_choose\":\"0\",\"status\":\"true\"},{\"total_cost\":95,\"sub_category\":[{\"cost\":0,\"sub_cat_name\":\"Hand\",\"sub_cat_id\":\"3\",\"service_cost\":\"20.00\",\"service_cat_id\":\"2\"},{\"cost\":0,\"sub_cat_name\":\"Body\",\"sub_cat_id\":\"4\",\"service_cost\":\"75.00\",\"service_cat_id\":\"2\"}],\"service_name\":\"Dressing\",\"service_id\":\"2\",\"is_multiple_choose\":\"1\",\"status\":\"true\"},{\"total_cost\":0,\"sub_category\":[{\"cost\":0,\"sub_cat_name\":\"No\",\"sub_cat_id\":\"7\",\"service_cost\":\"0.00\",\"service_cat_id\":\"3\"}],\"service_name\":\"Do you need oxygen?\",\"service_id\":\"3\",\"is_multiple_choose\":\"0\",\"status\":\"true\"},{\"total_cost\":30,\"sub_category\":[{\"cost\":0,\"sub_cat_name\":\"Level 3\",\"sub_cat_id\":\"10\",\"service_cost\":\"30.00\",\"service_cat_id\":\"4\"}],\"service_name\":\"Lift\\\/Stairs Accessibility\",\"service_id\":\"4\",\"is_multiple_choose\":\"0\",\"status\":\"true\"},{\"total_cost\":220,\"sub_category\":[{\"cost\":0,\"sub_cat_name\":\"Ventilator\",\"sub_cat_id\":\"12\",\"service_cost\":\"100.00\",\"service_cat_id\":\"5\"},{\"cost\":0,\"sub_cat_name\":\"Intracenous (IV) drip\",\"sub_cat_id\":\"13\",\"service_cost\":\"120.00\",\"service_cat_id\":\"5\"}],\"service_name\":\"Other Medical\",\"service_id\":\"5\",\"is_multiple_choose\":\"1\",\"status\":\"true\"},{}]","tripdatetime":"2019-03-27 10:57:51","address_to":"19\/20, Chanakyapuri, Ahmedabad, Gujarat 382481, India","notification_date_time":"28-03-2019 17:24:09"}

Окончательный JSON:

Replace all back slash and invalid double quotes : {"content-available":"1","notification_type":"end_request","booking_id":"247","priority":"high","base_price":"35","totalMinutePrice":"1.5","alert":"End trip By driver","sound":"default","title":"End trip By driver","total_amount":"397","address_from":"A/ 4 forum bungalow Nr. Hicort, Sola, Ahmedabad, Gujarat 380015, India","service_cost":"360","servicesList":[{"total_cost":15,"sub_category":[{"cost":0,"sub_cat_name":"Doctors on call","sub_cat_id":"1","service_cost":"15.00","service_cat_id":"1"}],"service_name":"Services1","service_id":"1","is_multiple_choose":"0","status":"true"},{"total_cost":95,"sub_category":[{"cost":0,"sub_cat_name":"Hand","sub_cat_id":"3","service_cost":"20.00","service_cat_id":"2"},{"cost":0,"sub_cat_name":"Body","sub_cat_id":"4","service_cost":"75.00","service_cat_id":"2"}],"service_name":"Dressing","service_id":"2","is_multiple_choose":"1","status":"true"},{"total_cost":0,"sub_category":[{"cost":0,"sub_cat_name":"No","sub_cat_id":"7","service_cost":"0.00","service_cat_id":"3"}],"service_name":"Do you need oxygen?","service_id":"3","is_multiple_choose":"0","status":"true"},{"total_cost":30,"sub_category":[{"cost":0,"sub_cat_name":"Level 3","sub_cat_id":"10","service_cost":"30.00","service_cat_id":"4"}],"service_name":"Lift/Stairs Accessibility","service_id":"4","is_multiple_choose":"0","status":"true"},{"total_cost":220,"sub_category":[{"cost":0,"sub_cat_name":"Ventilator","sub_cat_id":"12","service_cost":"100.00","service_cat_id":"5"},{"cost":0,"sub_cat_name":"Intracenous (IV) drip","sub_cat_id":"13","service_cost":"120.00","service_cat_id":"5"}],"service_name":"Other Medical","service_id":"5","is_multiple_choose":"1","status":"true"},{}],"tripdatetime":"2019-03-27 10:57:51","address_to":"19/20, Chanakyapuri, Ahmedabad, Gujarat 382481, India","notification_date_time":"28-03-2019 17:24:09"}

Полный код: MyFirebaseMessagingService.java

Надеюсь, это поможет другим.

0 голосов
/ 29 марта 2019

Это просто, у вас должен быть просто абстрактный объект Уведомления с атрибутами alert, title и notification_type. И затем, пока у вас есть конкретные реализации, основанные на ваших возможных типах:

  • AcceptRequestNotification extends Notification только с int booking_id (это тот, который у вас уже есть, тот, который вы назвали CommonNotificationBean)
  • EndRequestNotification extends Notification, который содержит, например, ArrayList с именем servicesList, этот ArrayList должен иметь тип Service, и тогда служба будет иметь атрибуты: service_id, service_name, status, sub_category который является еще одним ArrayList пользовательского типа.

И тогда вы просто измените свой код на:

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

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