I am having trouble to figure out why saving the following object to a .json file with Gson throws a StackOverflowError. Am I having a circular reference somewhere?
This is the object I am trying to save with Gson:
public class LocationConfig {
private HashSet<Warp> warps = new HashSet<>();
public LocationConfig() {
warps.add(new Warp("placeholder", false, new Location(Bukkit.getWorld("world"), 0, 0, 0)));
}
// getter and setter
}
The class LocationConfig uses the following Warp class in its HashSet warps:
public class Warp {
private String name;
private boolean ifListed;
private Location loc;
public Warp(String name, boolean ifListed, Location loc) {
this.name = name;
this.ifListed = ifListed;
this.loc = loc;
}
// getter and setter
}
I am using the following to save an LocationConfig Object:
// config is an object of the type LocationConfig
if (config != null) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try (FileWriter writer = new FileWriter(path)) {
gson.toJson(config, writer);
} catch (IOException e) {
e.printStackTrace();
}
}
The error I get while performing gson.toJson(config, writer):
[16:12:42] [Server thread/WARN]: java.lang.StackOverflowError
[16:12:42] [Server thread/WARN]: at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:383)
[16:12:42] [Server thread/WARN]: at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:378)
repeating very often
[16:12:42] [Server thread/WARN]: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:158)
[16:12:42] [Server thread/WARN]: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
[16:12:42] [Server thread/WARN]: at com.google.gson.Gson.getAdapter(Gson.java:423)
[16:12:42] [Server thread/WARN]: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
[16:12:42] [Server thread/WARN]: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
[16:12:42] [Server thread/WARN]: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
[16:12:42] [Server thread/WARN]: at com.google.gson.Gson.getAdapter(Gson.java:423)
repeating very often
Thank you!
Locationclass contain a reference toWarp? Can you also describeLocation? - Adwait KumarLocationdefinitely does not contain a reference to Warp.Locationcontains doubles (x,y,z), a Vector describing the direction and a World object (also not referencing toWarpin any way). - JakobLocationConfig. - JakobLocation,World. Maybe the possible circular ref is not related to any shown classes anyhow. Maybe it is between some other classes. So, how do possible answerers reproduce this problem? - pirho