如何在Android中解析Json数据以用于Firebase Cloud Messaging(FCM) [英] How to parse Json data in android for Firebase Cloud Messaging (FCM)

查看:85
本文介绍了如何在Android中解析Json数据以用于Firebase Cloud Messaging(FCM)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用FCM来发送推送消息,并处理onMessageReceived中所有传入的推送通知.现在的问题是解析此函数remoteMessage.getData()

i am using FCM for push messages and handling all incoming push notification in onMessageReceived. Now the issue is with parsing nested json that comes inside this function remoteMessage.getData()

我在设备中有以下阻止作为推送通知.数据有效负载的内容可能会有所不同,这里是稍后的经销商,可能是productInfo

I have following block coming as a push notification in device. content of data payload could be varied here it is dealer later on it can be 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>,所以不确定我的嵌套块是否正在转换为字符串.

now i am getting data with blackslashes as remoteMessage.getData() returns Map<String,String> so probably my nested block is being converted in string not sure though.

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

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

and if i write object = new JSONObject(remoteMessage.getData().toString()); then it got failed with following notification

{
  "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有效使用

Also make sure your JSON is valid use This

这篇关于如何在Android中解析Json数据以用于Firebase Cloud Messaging(FCM)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆