2016-10-14 14 views
0

Firebase Android:RemoteMessage経由でデータにネストされたパラメータにアクセスするにはどうすればよいですか?このビア形状

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

は、どのように私は、 "URL" と "テキスト" にアクセスすることができますか?

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

は私を取得します。

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

が、どのように、私は深くドリルのですか?

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

doesntのはかなりの仕事...私も試みたJSONObject:

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

が、これは...私がキャッチミスをしてみてください与え

いつものように大幅に高く評価される任意の助けと方向!

答えて

1

gsonを使用してモデルクラスを定義します。リモートメッセージにはMap<String, String>があり、それらはjsonオブジェクトを作成するためのコンストラクタと一致しません。

は、あなたのbuild.xmlにgsonを追加します。

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

    } 

} 

は、リモートメッセージから通知オブジェクトをデシリアライズ。

すべてのカスタムキーはトップレベルにある場合:カスタムJSONデータは、例えば、単一のキーにネストされている

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

場合は、「データ」、次に使用します。

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

注フィールド名がjsonのキーと正確に一致するので、この単純なケース@SerializedName()の注釈は不要ですが、たとえばキー名がstart_timeの場合、JavaフィールドstartTimeの名前を付けるにはアノテーションが必要です。

0

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) 
関連する問題