Ruby on Rails从fcm响应中获取body对象

时间:2018-01-02 06:53:14

标签: ruby-on-rails firebase-cloud-messaging

我在rails ruby​​ on rails上实现了推送通知的fcm。但是我收到了send()的响应,格式如下。我只需要body属性的值。我对rails上的ruby很新。请指导我如何实现它。

fcm = FCM.new(server_key)   
options = {
        priority: "high",
        # collapse_key: "updated_score",
        notification: {
            title: "Hi Android",
            body: "Hi, Worked perfectly"
        }
    }
response = fcm.send([device_token], options)

这是我的回复

{
  "success": true,
  "data": {
    "body": "{\"multicast_id\":8218758506962978728,\"success\":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"0:1514875371230492%ebb60861ebb60861\"}]}",
    "headers": {
      "content-type": [
        "application/json; charset=UTF-8"
      ],
      "date": [
        "Tue, 02 Jan 2018 06:42:51 GMT"
      ],
      "expires": [
        "Tue, 02 Jan 2018 06:42:51 GMT"
      ],
      "cache-control": [
        "private, max-age=0"
      ],
      "x-content-type-options": [
        "nosniff"
      ],
      "x-frame-options": [
        "SAMEORIGIN"
      ],
      "x-xss-protection": [
        "1; mode=block"
      ],
      "server": [
        "GSE"
      ],
      "alt-svc": [
        "hq=\":443\"; ma=2592000; quic=51303431; quic=51303339; quic=51303338; quic=51303337; quic=51303335,quic=\":443\"; ma=2592000; v=\"41,39,38,37,35\""
      ],
      "accept-ranges": [
        "none"
      ],
      "vary": [
        "Accept-Encoding"
      ],
      "connection": [
        "close"
      ]
    },
    "status_code": 200,
    "response": "success",
    "canonical_ids": [],
    "not_registered_ids": []
  }
}

2 个答案:

答案 0 :(得分:1)

您可以关注ruby OpenStruct库,它是这样的

object = JSON.parse(response, object_class: OpenStruct)

然后你可以根据对象值找到并非常好地解释here

希望能提供帮助

答案 1 :(得分:0)

假设您的回复是hash

body =  hash[:data][:body].gsub(/[\"]/,"")

和out put将是这样的: -

"{multicast_id:8218758506962978728,success:1,failure:0,canonical_ids:0,results:[{message_id:0:1514875371230492%ebb60861ebb60861}]}"