android - 如何在 Android 中为 Firebase 云消息传递 (FCM) 解析 Json 数据

标签 android json firebase firebase-cloud-messaging

我正在使用 FCM用于推送消息并处理 onMessageReceived 中的所有传入推送通知。现在的问题是解析这个函数中的嵌套 json remoteMessage.getData()

我有以下 block 作为设备中的推送通知。数据有效载荷的内容可以在这里改变它是稍后的经销商它可以是productInfo

{
  "to": "/topics/DATA",
  "priority": "high",
  "data": {
    "type": 6,
    "dealerInfo": {
      "dealerId": "358",
      "operationCode": 2
    }
  }
}

我是这样解析的

 if(remoteMessage.getData()!=null){

        JSONObject object = null;
        try {
            object = new JSONObject(remoteMessage.getData());       

        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

现在我正在获取带有黑斜杠的数据 remoteMessage.getData()返回 Map<String,String>所以可能我的嵌套 block 正在转换为字符串,但不确定。

{
  "wasTapped": false,
  "dealerInfo": "{\"dealerId\":\"358\",\"operationCode\":2}",
  "type": "6"
}

如果我写 object = new JSONObject(remoteMessage.getData().toString());然后失败并显示以下通知

{
  "to": "regid",
  "priority": "high",
  "notification" : {
      "body": "Message Body",
      "title" : "Call Status",
      "click_action":"FCM_PLUGIN_ACTIVITY"
   },
  "data": {
    "type": 1,
     "callNumber":"ICI17012702",
     "callTempId":"0",
      "body": "Message Body",
      "title" : "Call Status"
  }
}

错误 我得到的是

> org.json.JSONException: Unterminated object at character 15 of
> {body=Message Body, type=1, title=Call Status, callNumber=ICI17012702,
> callTempId=0}

最佳答案

试试这段代码:

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

还要确保您的 JSON 有效使用 This

关于android - 如何在 Android 中为 Firebase 云消息传递 (FCM) 解析 Json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42274398/

相关文章:

java - 无法使用 getApplication 方法转换为 Application

java - Android 寻呼机适配器,onClick

ruby - 如何在 Ruby 1.9 中将 Hash 转换为 JSON 字符串?

json - ElasticSearch JSON期望

swift - 想要像实时数据库一样获取 firestore

ios - Firebase Auth 仅适用于使用我的应用的设备

android - 在数据库做一些繁重的后台工作时卡住和应用程序的最佳方法?

java - 致命异常主要 - 应用程序在启动时崩溃

json - Swift Codable 解码更改 JSON 并忽略某些字段

java - 使用 Firebase 列表适配器读取和写入 Firebase 数据库