ajay
ajay

Reputation: 9680

Respond to invalid JSON requests with application/json type response

I am using Play framework 2.2.3. I want to respond to invalid JSON requests with a JSON response saying response type is invalid JSON like

{"message": "invalid json"}

but Play by default sends html data. I am using

@BodyParser.Of(BodyParser.Json.class)

annotation for my action method in the controller class. How do I send a JSON response instead of the default html response?

Upvotes: 0

Views: 1459

Answers (1)

biesior
biesior

Reputation: 55798

Play automaticaly sets content type depending on type of returned data, so use valid JSON object, you don't need to use @BodyParser for that, badRequest additionally sets response status to 400

public static Result someAction() {
    ObjectNode answerObj = Json.newObject();
    answerObj.put("message", "invalid json");
    return badRequest(answerObj);
}

Upvotes: 1

Related Questions