簡體   English   中英

Firebase Android:如何通過 RemoteMessage 訪問嵌套在數據中的參數?

[英]Firebase Android: how do I access params nested in data via RemoteMessage?

通過這個形狀:

{
  "to": "000",
  "priority": "high",
  "data": {
    "title": "A Title",
    "message": "A Message",
    "link": {
      "url": "http://www.espn.com",
      "text": "ESPN",
    }
  }
}

如何訪問“url”和“text”?

String messageLink = remoteMessage.getData().get("link");

讓我:

{"text":"ESPN","url":"http://www.espn.com"}

但我如何鑽得更深?

remoteMessage.getData().get("link").get("text");

不太工作......我也嘗試過JSONObject:

JSONObject json = new JSONObject(remoteMessage.getData());    
JSONObject link = json.getJSONObject("link");

但這讓我嘗試捕捉錯誤...

一如既往的任何幫助和指導,我們將不勝感激!

我會使用 gson 並定義一個模型類。 遠程消息為您提供Map<String, String>並且它們不是用於創建 json 對象的匹配構造函數。

將 gson 添加到您的 build.xml 中:

compile 'com.google.code.gson:gson:2.5'

創建通知模型:

import com.google.gson.annotations.SerializedName;

public class Notification {

    @SerializedName("title")
    String title;
    @SerializedName("message")
    String message;
    @SerializedName("link")
    private Link link;

    public String getTitle() {
        return title;
    }

    public String getMessage() {
        return message;
    }

    public Link getLink() {
        return link;
    }

    public class Link {

        @SerializedName("url")
        String url;
        @SerializedName("text")
        String text;

        public String getUrl() {
            return url;
        }

        public String getText() {
            return text;
        }

    }

}

從遠程消息反序列化一個通知對象。

如果您的所有自定義鍵都在頂級:

Notification notification = gson.fromJson(gson.toJson(remoteMessage.getData()), Notification.class);

如果您的自定義 json 數據嵌套在單個鍵中,例如“數據”,則使用:

Notification notification = gson.fromJson(remoteMessage.getData().get("data"), Notification.class);

請注意,在這種簡單的情況下, @SerializedName()注釋是不必要的,因為字段名稱與 json 中的鍵完全匹配,但是如果您例如有一個鍵名start_time但您想命名 java 字段startTime您將需要該注釋。

從 GCM 遷移到 FCM 時遇到了這個問題。

以下內容適用於我的用例,所以也許它對你有用。

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)

就這么簡單:

String linkData = remoteMessage.getData().get("link");
JSONObject linkObject = new JSONObject(linkData);

String url = linkObject.getString("url");
String text = linkObject.getString("text");

當然,還有適當的錯誤處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM