Responder a solicitudes JSON no válidas con respuesta de tipo aplicación/json

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?

preguntado el 28 de mayo de 14 a las 12:05

1 Respuestas

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

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

contestado el 28 de mayo de 14 a las 15:05

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 no es application/json? - ajay

If you are sure that body is a JSON-like String you can just parse it: JsonNode node = Json.parse(request().body()); - bisior

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

Use try/catch block then, Json.parse() throws an exception if it can't parse valid JSON string - bisior

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 - bisior

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.