Search code examples
javaandroidgoogle-cloud-messagingandroid-bundle

Parse Bundle data


I'm using GCM in my app and I'm sending some datas from server to client. The data is this:

{ 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': []
}

I'm getting this data in my GcmListener:

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

How can I parse this data to an object? I couldn't find so much information and I'm searching this for hours.

Thanks.


Solved. This article helped and I used JSON.stringfiy in server.

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


Solution

  • This is a basic example using 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");
    }