Type adapters

For when we can't serialize your classes back to Java.

If you got a Config(De)SerializationException explaining that SC-CFG could not (de)serialize your field, this is probably what you are looking for. By creating a type adapter, you tell sc-cfg how to serialize and deserialize a certain type.

By default, sc-cfg comes with some pre-configured type adapters, but you can always provide custom adapters for any type, and if it happens that one of your type adapter clash with the default ones, your type adapter will override the default one, this is already handled, you don't have to do anything.

Automatically register type adapters

Register type adapters for your custom types simply by annotating them with @RegisterTypeAdapter.

import com.github.secretx33.sccfg.api.annotation.RegisterTypeAdapter;
import com.google.gson.JsonSerializer;

// this adapter is automatically registered
@RegisterTypeAdapter(YourCustomClass.class)
public class ClassAdapter implements JsonSerializer<YourCustomClass>, JsonDeserializer<YourCustomClass> {
    // ...
}

Manually register type adapters

Sometimes, we have a very specific type that uses parameterized types, which our RegisterTypeAdapter annotation does not support. If that happens to you, worry not! You can still register your type adapters.

import com.google.gson.reflect.TypeToken;

public class MyPlugin extends JavaPlugin {
    
    @Override
    public void onEnable() {
        final Type type = new TypeAdapter<YourCustomType<List<String>>>() {}.getType();
        // register one type adapter
        Config.registerTypeAdapter(type, new YourCustomTypeAdapter());

        // register multiple type adapters at once
        final Map<? extends Type, Object> typeAdapters = new HashMap<>();
        typeAdapters.put(SomeClass.class, AdapterForSomeClass());
        typeAdapters.put(type, YourCustomTypeAdapter());
        Config.registerTypeAdapters(typeAdapters);
    }
}

Last updated