10

I have this:

get ("/test", (req, resp) -> {
    return repository.getAll();
}, new JsonTransformer());

My transformer looks like:

public class JsonTransformer implements ResponseTransformer {

    ObjectMapper om = new ObjectMapper();

    public JsonTransformer() {
    }

    @Override
    public String render(Object o) throws Exception {
        return om.writeValueAsString(o);
    }
}

I've tried adding a header using the header funtion on response like so:

get ("/test", (req, resp) -> {
    resp.header("Content-Type", "application/json");
    return repository.getAll();
}, new JsonTransformer());

And I've tried this which I found in the docs: I think this sets the accept-type

get ("/test", "application/json", (req, resp) -> {
    return repository.getAll();
}, new JsonTransformer());

But nowhere I'm getting application/json as my Content-Type header

albertjan
  • 7,739
  • 6
  • 44
  • 74

3 Answers3

17

Well after researching I found an elegant way to resolve this, I created an before method.

before((request, response) -> response.type("application/json"));

This would add the response type to json.

You can add it in after route but it may become troublesome later on. thx albertjan for your tip :)

Gabriel
  • 2,011
  • 14
  • 14
  • 1
    If json is your primary response-type the before route is a good solution. The after route could become troublesome later on. – albertjan Jan 06 '15 at 10:03
  • Thanks for your reply, I did try both but i ended up using before as it was cleaner and i still have the opportunity to change the response.type in the route itself if needed. – Gabriel Jan 06 '15 at 18:23
6

You set the Content-Type of the response using the response.type function like so:

get("test", (req, resp) -> {
    resp.type("application/json");
    return repository.getAll() 
}, new JsonTransformer());
albertjan
  • 7,739
  • 6
  • 44
  • 74
2

The third option is to use an after filter:

after((request, response) -> response.type("application/json"));

Please see: http://sparkjava.com/documentation#filters