-
Notifications
You must be signed in to change notification settings - Fork 50
Storage
Prison-Core includes a very simple storage library that you may use to serialize JSON save files. JSON is the standard save format for Prison, and it is highly recommended that you use it. This guide will show you how to use the Prison-Core Storage API to do just that.
Data is saved by storing the variables inside classes in JSON files. This is called serialization. It's very easy to make your class JSON-serializable. Just have it extend AbstractJsonable<>
, with the class name being the generic parameter:
public class Guard extends AbstractJsonable<Guard> {
public String name;
public boolean onDuty;
public Guard() {}
public Guard(String name, boolean onDuty) {
this.name = name;
this.onDuty = onDuty;
}
}
Notice that you must include a parameterless constructor in order for the serialization to work. Also, notice that your generic parameter for AbstractJsonable
must be the same class you are creating.
Sometimes, you want to make variables but you don't want them to be serialized. To do this, just add the @Exclude
annotation to the variable.
public class Guard extends AbstractJsonable<Guard> {
private String name;
@Exclude
private int hoursOnline;
// ...
}
Now, it's time to write your file to disk. To do this, just call the toFile(File)
method on an instance of your Jsonable class.
Guard guard = new Guard("John", false);
try {
guard.toFile(new File(myModule.get().getDataFolder(), "john.guard.json"));
} catch(IOException e) {
// The file failed to save - tell the user here.
}
Note that the file will be created for you if it doesn't already exist.
Alternatively, you could just call toJson()
, which returns a String of the raw JSON.
So, you've saved a file called john.guard.json to disk. Now, you want to load it in. This is an easy task.
Guard guard = new Guard();
guard = guard.fromFile