Skip to content

Customize FX Gson

Joffrey Bion edited this page Oct 25, 2016 · 6 revisions

Observable collections implementation override

Sometimes you're not satisfied by the default implementation used for the deserialization of observable collections (ArrayList, HashMap, HashSet).

If you use a different implementation for your observable collections of a particular type (say, ObservableList), then, in order for FX Gson to use your own implementation, you need to register your own Serializer or TypeAdapter (see Gson documentation) to this GsonBuilder:

GsonBuilder builder = FxGson.coreBuilder().registerTypeAdapter(ObservableList.class, new MyCollectionTypeAdapter());

Note that this will affect all ObservableLists. If you only want to override the implementation of the observable collection contained in a particular class MyClass, then you need to specify your own Serializer or TypeAdapter for that class instead of the collection class itself:

GsonBuilder builder = FxGson.coreBuilder().registerTypeAdapter(MyClass.class, new MyClassTypeAdapter());

Where MyClassTypeAdapter handles the deserialization of the field of the collection class you want.

I don't need all that

More often than not, the built-in stuff is not what you need. Fortunately, FxGson is simply a helper class registering a particular TypeAdapterFactory on a GsonBuilder.

If you need more control, you can use directly or even extend the JavaFxPropertyTypeAdapterFactory or JavaFxExtraTypeAdapterFactory yourself.

Going one step further, you may even restrict your choice to only the TypeAdapters/InstanceCreators you need, by registering them manually on your own GsonBuilder:

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(ObservableList.class, new ObservableListCreator());
builder.registerTypeAdapter(StringProperty.class, new StringPropertyTypeAdapter());

You can find FX Gson's TypeAdapters/InstanceCreators in the packages org.hildan.fxgson.adapters and org.hildan.fxgson.creators.

Clone this wiki locally