-
Notifications
You must be signed in to change notification settings - Fork 11
Getting Started
Falkreon edited this page Jan 17, 2019
·
2 revisions
Via gradle:
repositories {
mavenCentral()
}
dependencies {
compile "blue.endless:jankson:1.1.0"
}
Loading a json file is just a matter of getting a Jankson instance and giving it a File, String, or InputStream. Additionally, it can pour the data into an ordinary Java object, so you can access your configs fluently.
public void loadConfig() {
Jankson jankson = Jankson.builder().build();
File configFile = new File("config.json");
JsonObject configJson = jankson.load(configFile);
ConfigObject configObject = jankson.fromJson(configJson, ConfigObject.class);
}
private class ConfigObject {
/* Comment annotations populate serialized keys with json5 comments */
@Comment("why orbs?")
public int maxOrbs = 10;
private List<String> someStrings = new ArrayList<>();
protected Map<String, String> uninitialized; //Still okay
}
Saving is quite similar. We just bake the config down to a String and write it out.
public void saveDefaultConfig() {
File configFile = new File(FabricLoader.INSTANCE.getConfigDirectory().toString()+"/mymod.json");
Jankson jankson = Jankson.builder().build();
String result = jankson
.toJson(new ConfigObject()) //The first call makes a JsonObject
.toJson(true, true, 0); //The second turns the JsonObject into a String -
//in this case, preserving comments and pretty-printing with newlines
try {
if(!configFile.exists()) configFile.createNewFile();
FileOutputStream out = new FileOutputStream(configFile, false);
out.write(result.getBytes());
out.flush();
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
And the default config winds up looking like this:
{
/* why orbs? */
"maxOrbs": 10,
"someStrings": [],
"uninitialized": null
}
If you're migrating from another json library, and just want to use Jankson to strip comments and quirks, you can just ask jankson to output standard json and keep your original workflow:
public void loadConfig() {
Jankson jankson = Jankson.builder().build();
File configFile = new File("config.json");
JsonObject configJson = jankson.load(configFile);
String regularized = configJson.toJson(false, false, 0);
ConfigObject object = new Gson().fromJson(regularized, ConfigObject.class);
}