Search code examples
javaandroidandroid-jsonandroid-parser

How to extract value from raw payload in android?


I am trying to extract google.sent_time from the following JSON , how do I get that value?
It seems like it's a raw payload, and not straightforward JSON, so wondering if there is a way to extract it?

{
  "notificationID": "677291f5-a784-43df-af2e-0067e9c",
  "title": "test 223",
  "body": "payload",
  "lockScreenVisibility": 1,
  "groupMessage": "",
  "fromProjectNumber": "819539062812",
  "priority": 5,
  "rawPayload": "{\"google.delivered_priority\":\"normal\",\"google.sent_time\":1591849563191,\"google.ttl\":259200,\"google.original_priority\":\"normal\",\"custom\":\"{\\\"i\\\":\\\"677291f5-a784-43df-af2e-0363a4067e9c\\\"}\",\"oth_chnl\":\"\",\"pri\":\"5\",\"vis\":\"1\",\"from\":\"819539062812\",\"alert\":\"payload\",\"title\":\"test 223\",\"grp_msg\":\"\",\"google.message_id\":\"0:1591849563205759%409ebbcaf9fd7ecd\",\"google.c.sender.id\":\"819539062812\",\"notificationId\":-1451117355}"
}

Solution

  • It is JSON, with some characters escaped so it can fit in to a string type field in your main JSON.

    You can extract the string value of "rawPayload" field an feed that to whatever JSON parser you are using, or you can use a regex directly on the string to get just the value:

    Here is a regex example:

    Pattern p = Pattern.compile("google\\.sent_time.*:(\\d+)");
    Matcher m = p.matcher(yourInputString);
    m.find();
    String sentTime = m.group(1);