JSON response from string in Javalin

Viewed 947

I am trying to create the response in JSON format from a string in Javalin. JSON object must be from a string, not from class.

public static void main(String[] args) {

    Javalin app = Javalin.create().start(9000);

    String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}";
    JsonObject jsonObject= JsonParser.parseString(jsonString).getAsJsonObject();
            
    app.error(404, ctx -> ctx.json(jsonObject));

    ...

}

With the code above, I am getting a 500 server error.

1 Answers

If you are using Gson, then switch to using Jackson, when using Javalin methods such as ctx.json().

If you used Maven to import Javalin, and if you used the javalin-bundle, then you will already have Jackson, for example:

<dependency>
    <groupId>io.javalin</groupId>
    <artifactId>javalin-bundle</artifactId>
    <version>3.13.3</version>
</dependency>

If you only used javalin and not javalin-bundle then you will need to add Jackson yourself - for example:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.2</version>
</dependency>

The following is the code from the question, but re-worked to use Jackson (and to use valid JSON):

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.javalin.Javalin;

public class App {

    public static void main(String[] args) throws JsonProcessingException {
        Javalin app = Javalin.create().start(9000);
        String jsonString = "{\"test1\":\"value1\",\"test2\":{\"id\":0,\"name\":\"testName\"}}";
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(jsonString);
        app.error(404, ctx -> ctx.json(jsonNode));
    }
}
Related