问题
I am working on Android application in which I am getting Json message through GCM and I am passing notification through Bundles. Everything is working fine and I am getting Bundles message in my notification tray.
But I want to parse that JSON Bundle message and it is given me an error:
Bundle of type java.lang.String cannot be converted to JSONArray
My JSON Response coming through Bundles is given below along with the code.
Bundle[{summary=Game update 49ers touchdown, android.support.content.wakelockid=1, collapse_key=do_not_collapse, from=931953845039, lastplay=5yd run up the middle}]
Service Class:
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private static final String TAG = "PubnubGcm";
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " +
extras.toString());
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
sendNotification(extras.toString());
try {
JSONArray jsonArray = new JSONArray(extras.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
System.out.println(c.getString("summary"));
/*System.out.println(c.getString(APP_URL));
System.out.println(c.getString(APP_NAME));
System.out.println(c.getString(APP_IMAGE));
System.out.println(c.getString(IMAGE_TYPE));
System.out.println(c.getString(APP_TRACK));*/
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
来源:https://stackoverflow.com/questions/26828411/bundle-of-type-java-lang-string-cannot-be-converted-to-jsonarray