如何解析Android中的Json数据for Firebase Cloud Messaging(FCM)

Hun*_*unt 12 android json firebase firebase-cloud-messaging

FCM用于推送消息和处理onMessageReceived中的所有传入推送通知.现在的问题是解析嵌入在这个函数中的嵌入式jsonremoteMessage.getData()

我有以下块作为设备中的推送通知.数据有效载荷的内容可以在这里变化,这是经销商以后可以productInfo

{
  "to": "/topics/DATA",
  "priority": "high",
  "data": {
    "type": 6,
    "dealerInfo": {
      "dealerId": "358",
      "operationCode": 2
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我如何解析它

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

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

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


    }
Run Code Online (Sandbox Code Playgroud)

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

{
  "wasTapped": false,
  "dealerInfo": "{\"dealerId\":\"358\",\"operationCode\":2}",
  "type": "6"
}
Run Code Online (Sandbox Code Playgroud)

如果我写,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"
  }
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误

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

raf*_*007 12

试试这段代码:

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
      }
   }
Run Code Online (Sandbox Code Playgroud)

另外,还要确保您的JSON是有效的利用

  • 好吧,如果您有一个带有一层嵌套的JSON对象,那么它可以完美地工作。一旦具有两个或多个嵌套级别,FCM就会将嵌套的JSON对象转换为字符串。解析并打印时,它将成为转义的字符串,而不是JSON对象。您在此处编写的确切代码可以解决此问题。 (2认同)

gon*_*nga 5

从GCM迁移到FCM时遇到此问题。

以下内容适用于我的用例(和OP有效负载),因此也许适用于其他用户。

JsonObject jsonObject = new JsonObject(); // com.google.gson.JsonObject
JsonParser jsonParser = new JsonParser(); // com.google.gson.JsonParser
Map<String, String> map = remoteMessage.getData();
String val;

for (String key : map.keySet()) {
    val = map.get(key);
    try {
        jsonObject.add(key, jsonParser.parse(val));
    } catch (Exception e) {
        jsonObject.addProperty(key, val);
    }
}

// Now you can traverse jsonObject, or use to populate a custom object:
// MyObj o = new Gson().fromJson(jsonObject, MyObj.class)
Run Code Online (Sandbox Code Playgroud)