Skip to content

Customize FX Gson

Joffrey Bion edited this page Feb 7, 2017 · 6 revisions

Using FxGsonBuilder for more options

The "basic usage" section is in fact a handful of shorthands to create and configure an FxGsonBuilder. The core and full builder described there can also be obtained this way:

Gson fxGson = new FxGsonBuilder().create();
Gson fxGsonWithExtras = new FxGsonBuilder().withExtras().create();

GsonBuilder coreBuilder = new FxGsonBuilder().builder();
GsonBuilder fullBuilder = new FxGsonBuilder().withExtras().builder();

Using the FxGsonBuilder manually allows a finer control over the created Gson or GsonBuilder.

For instance you may avoid NullPrimitiveExceptions by allowing null values for properties of primitive types during deserialization:

Gson gson = new FxGsonBuilder().acceptNullPrimitives().create();

Using this Gson, we can deserialize an IntegerProperty called number from this JSON: {"number": null}. It will produce an IntegerProperty with the default initialization value for int, which is 0.

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();
builder.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();
builder.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

Sometimes, the built-in stuff is not what you need. Fortunately, FxGson simply registers a particular TypeAdapterFactory on a GsonBuilder.

If you need more control, you can manually register the JavaFxPropertyTypeAdapterFactory or JavaFxExtraTypeAdapterFactory yourself, or create your own factory extending one of those.

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 respectively.