Does sponge provide a service which could handle (de)serializing object states (such as Entity, ItemStack,…) to json/xml?
Yep!
You’ll want to use ConfigurateTranslator
to translate serializables to ConfigNodes, and then Configurate can be written as a json. I’m not sure if it supports xml though… You’d end up with something like this:
public static String toJson(ConfigurationNode node) throws IOException {
StringWriter writer = new StringWriter();
GsonConfigurationLoader.builder().build().saveInternal(node, writer); //I'm not totally positive on this line, I think this is right....
return writer.toString();
}
public static String serializeToJson(DataContainer container) throws IOException {
return toJson(ConfigurateTranslator.instance().translateData(container));
}
public static <T extends DataSerializable> Optional<T> deSerializeJson(String json, Class<T> type) throws IOException {
DataView target = ConfigurateTranslator.instance().translateFrom(GsonConfigurationLoader.builder().setSource(() -> new BufferedReader(new StringReader(json))).build().load());
DataManager manager = Sponge.getGame().getDataManager();
return manager.deserialize(type, target); //I think this may be outdated by now, but the concept is still the same
}