0

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?

biesior
  • 55,576
  • 10
  • 125
  • 182
ajay
  • 9,402
  • 8
  • 44
  • 71
  • might help you. http://stackoverflow.com/questions/10699595/how-to-manually-throw-error-pages-in-play-framework – MjZac May 28 '14 at 11:52

1 Answers1

1

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);
}
biesior
  • 55,576
  • 10
  • 125
  • 182
  • Thank you. I am trying to get the JSON payload in the request as `JsonNode json = request().body().asJson();` assuming that content-type is `application/json`. How do I handle for cases when the `content-type` is not `application/json`? – ajay May 30 '14 at 16:49
  • If you are sure that body is a JSON-like String you can just parse it: `JsonNode node = Json.parse(request().body())`; – biesior May 30 '14 at 17:50
  • But I also have to handle cases when the body is not JSON. It can be html, xml etc. In those cases, I want to send a message saying only JSON content type is allowed. Please help. – ajay May 30 '14 at 18:33
  • 1
    Use try/catch block then, Json.parse() throws an exception if it can't parse valid JSON string – biesior May 30 '14 at 18:45
  • Thanks. That did it. Just a question - how do I accept only one HTTP method like POST and send JSON response for other methods instead of letting Play send html data for 404 error? – ajay May 30 '14 at 18:54
  • 1
    Create additional action for GET method and return JSON with `badRequest()` simple solutions are nice, cause they are nice and simple :) Optionally you can override some method of Global object ie. `onHandlerNotFound` – biesior May 30 '14 at 19:01