Skip to content

Using Jankson as a Gson Preprocessor

If you're migrating from another JSON library, and just want to use Jankson to strip comments and utilize quirks, you can just ask Jankson to output standard JSON and keep your original workflow.

import blue.endless.jankson.Jankson;
import java.io.File;

class Config {
    // Other code...

    public static Config loadConfig() {
        // Create a new Jankson instance
        // (This can also be a static instance, defined outside the function)
        var jankson = Jankson.builder().build();

        // Get the config file
        var configFile = new File("config.json");
        // Parse the config file into a JsonObject
        var configJson = jankson.load(configFile);
        // Normalize the JsonObject into a String
        var normalized = configJson.toJson(false, false);

        // Create or get an instance of Gson
        return new Gson()
            // Use it to convert the string to an instance of your POJO
            .fromJson(normalized, Config.class);
    }
}
import blue.endless.jankson.Jankson
import java.io.File

// Other code...

fun loadConfig(): Config? {
    // Create a new Jankson instance
    // (This can also be a static instance, defined outside the function)
    val jankson: Unit = Jankson.builder().build()

    // Get the config file
    val configFile = File("config.json")
    // Parse the config file into a JsonObject
    val configJson: Unit = jankson.load(configFile)
    // Normalize the JsonObject into a String
    val normalized: Unit = configJson.toJson(false, false)

    // Create or get an instance of Gson
    return Gson()
        // Use it to convert the string to an instance of your POJO
        .fromJson(normalized, Config::class.java)
}
import blue.endless.jankson.Jankson

// Other code

static Config loadConfig() {
    // Create a new Jankson instance
    // (This can also be a static instance, defined outside the function)
    var jankson = Jankson.builder().build()

    // Get the config file
    var configFile = new File("config.json")
    // Parse the config file into a JsonObject
    var configJson = jankson.load(configFile)
    // Normalize the JsonObject into a String
    var normalized = configJson.toJson(false, false)

    // Create or get an instance of Gson
    return new Gson()
    // Use it to convert the string to an instance of your POJO
            .fromJson(normalized, Config.class)
}