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
Spark is a compact framework for building web applications that run on the JVM. It comes with an embedded web server, Jetty, so you can get started in minutes.
In the Spark lingo, a route is a handler A route is a URL pattern that is mapped to a handler. A handler can be a physical file or a $ gradle run. We run the application with gradle run command. An embedded Jetty server is started. $ curl localhost:4567/hello Hello there!
Stopping the Server By calling the stop() method the server is stopped and all routes are cleared.
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());
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With