2015-06-03 42 views
1

我在我的應用中使用GCM,並且正在將一些數據從服務器發送到客戶端。數據是這樣的:解析綁定數據

{ registration_id: '', 
    time_to_live: 60, 
    'data.type': 'newProcess', 
    'data.sessionId': 'fd1eceb1-e065-4d9e-9bda-50aecaf89b68', 
    'data.questions': 
    [ { question: 'q', answers: ['a', 'b', 'c'], correctAnswer: 1 }, 
    { question: 'k', answers: ['a', 'b', 'c'], correctAnswer: 1 } ], 
    'data.users': [] 
} 

我得到我的GcmListener這樣的數據:

@Override 
public void onMessageReceived(String from, Bundle data) { 
    //parse the data that come from server 
} 

我怎麼能這個數據解析到一個對象?我無法找到這麼多的信息,我正在尋找這個小時。

謝謝。


已解決。這篇文章幫助我在服務器中使用了JSON.stringfiy。

http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html

回答

4

這是使用JSONObject一個基本的例子:

@Override 
public void onMessageReceived(String from, Bundle data) { 

    String myJSONString = data.getString("myJSON"); 

    JSONObject myJson = new JSONObject(myJSONString); 

    int registration_id = myJson.optInt("registration_id "); 
    String time_to_live = myJson.optString("time_to_live"); 
} 
+1

我檢查它。 – Lazy