Support for custom objects in ListOption
TechPro424 opened this issue ยท 4 comments
Currently, an ArrayList<custom object class>
does not seem to work as a valid config entry
For example, if I have a custom class such as
public class CustomObject {
String a = "abcd"
ArrayList<String> b = new ArrayList<String>()
}
And the following config entry
@ConfigEntry public ArrayList<CustomObject> customObjects = new ArrayList<CustomObject>();
And a method to add new CustomObject
s to the group
public void addNewCustomObjectToConfig(String name, String[] strings1) {
ArrayList<String> strings2 = new ArrayList<String>();
for (String string : strings1) {
strings2.add(player);
}
CustomObject newCustomObject = new CustomObject(name, strings2);
customObjects.add(newCustomObject);
configInstance.save();
}
Whenever I use this method in any other part of my code, only an empty object {}
gets added to the ArrayList<CustomObject>
Please add support for such custom objects
While I have heard that adding support for such custom objects is quite hard, I felt I should at least create an issue so that the requirement is documented here on GitHub.
This issue is based on this support forum post in the Discord server
I assume you are using GsonConfigInstance, which just used GSON, you have access to the GSON builder whilst constructing the instance.
Ok, but what can I do with the GSON Builder? Isn't that just used to set options like nice formatting or serializing null values?
Thanks. that fixed it! For those who have a similar issue, here is my type adapter:
import java.io.IOException;
import java.util.ArrayList;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
public class GroupTypeAdapter extends TypeAdapter<CustomObject> {
@Override
public CustomObject read(final JsonReader in) throws IOException {
CustomObject customObject = new CustomObject("abcd", new ArrayList<String>());
in.beginObject();
while(in.hasNext()) {
switch (in.nextName()) {
case "a":
customObject.a = in.nextString();
break;
case "b":
in.beginArray();
while(in.hasNext()) {
customObject.b.add(in.nextString());
}
in.endArray();
}
}
in.endObject();
return customObject;
}
@Override
public void write(final JsonWriter out, final CustomObject customObject) throws IOException {
out.beginObject();
out.name("a").value(customObject.a);
out.name("b").beginArray();
for (String string : customObject.b) {
out.value(string);
}
out.endArray();
out.endObject();
}
}