JSON from a String

25 Apr 2021

This is useful when testing web pages which consume Ajax-provided JSON.

I can define my JSON in a String and then use one of the below approaches to convert that into an object suitable to be processed as a JSON response to an Ajax request. In this way, I do not need to create custom POJOs or any nested maps/arrays.

Using Jackson

XML
1
2
3
4
5
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.1</version>
</dependency>
Java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;

...

private JsonNode getJson() throws JsonProcessingException {
    String jsonString = "your arbitrary JSON";
    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.readTree(jsonString);
}

Using Gson

XML
1
2
3
4
5
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.6</version>
</dependency>
Java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.LinkedHashMap;

...

// For a JSON object "{ ... }":
private LinkedHashMap getJsonObject() {
    String jsonObject = "your arbitrary JSON object";
    return new Gson().fromJson(jsonObject, LinkedHashMap.class);
}

// For a JSON array "[ ... ]":
private ArrayList getJsonArray() {
    String jsonArray = "your arbitrary JSON array";
    return new Gson().fromJson(jsonArray, ArrayList.class);
}

Javalin

I often use Javalin as my web app - in which case I use its built-in support for Jackson.

A basic Javalin set-up:

XML
1
2
3
4
5
<dependency>
    <groupId>io.javalin</groupId>
    <artifactId>javalin-bundle</artifactId>
    <version>3.13.6</version>
</dependency>
Java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import io.javalin.Javalin;
import io.javalin.http.Context;

...

public class App {
    public static void main(String[] args) {
        Javalin app = Javalin.create(config -> {
            config.enableCorsForAllOrigins(); // for testing only!
        }).start(7001);
        app.get("/test", ctx -> ctx.json(getJson()));  // uses Jackson
    }
}