tenticon
tenticon

Reputation: 2913

Spring - Rest controller handles json input as null string

While playing around with the facebook messenger api I created a simple REST controller

@RestController
public class ChatController 
{
    private static final Logger LOG = LoggerFactory.getLogger(ChatController.class);

    @RequestMapping(value="/webhook", method=RequestMethod.POST, consumes="application/json")
    public String onWebhookEvent(String event)
    {
        LOG.info("Received event {}",event);
        return "test";
    }
}

However, when I POST the following json to the the /webhook endpoint the event input is logged as null ("Received event null")

{"object":
    "page",
    "entry":[
        {
          "id":43674671559,
          "time":1460620433256,
          "messaging":[
            {"sender":{"id":123456789},
             "recipient":{"id":987654321},
             "timestamp":1460620433123,
             "message":{"mid":"mid.1460620432888:f8e3412003d2d1cd93","seq":12604,"text":"Testing Chat Bot .."}
            }
          ]
        }
    ]
}

Why is that and how can I fix that? Since json is a serialization mechanism I assumed it will be presented as string to the onWebhookEvent method.

Thanks for the help

Upvotes: 1

Views: 770

Answers (1)

Guy Smorodinsky
Guy Smorodinsky

Reputation: 952

If you want a request's body to be tied up to a parameter, use @RequestBody.

By the way, return a ResponseEntity object, as it is a wrapper to whatever you want to return, and you can specify additional information (for example, headers of the response)

Upvotes: 1

Related Questions