Skip to content

Basic FX Gson usage

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

Simple ways matter

The simplest way to use FX Gson is to directly create a Gson this way:

// to handle any type of JavaFX Property and Observable collections
Gson fxGson = FxGson.create();

// to also handle the Color & Font classes
Gson fxGsonWithExtras = FxGson.createWithExtras();

Using pre-configured GsonBuilders

Usually, you need a bit more configuration than that. That's why FxGson can also return a regular GsonBuilder so that you can add your own configuration to it:

Gson fxGson = FxGson.coreBuilder()
                    .registerTypeAdapterFactory(new MyFactory())
                    .disableHtmlEscaping()
                    .create();

Gson fxGsonWithExtras = FxGson.fullBuilder()
                              .registerTypeAdapter(Pattern.class, new PatternSerializer())
                              .setPrettyPrinting()
                              .create();

FX Gson's core and full builders are described more in details in the dedicated page.

You can find more details on how to configure a GsonBuilder in the Gson documentation.

Using FxGsonBuilder for more options

The above section is in fact a handful of shorthands to create and configure an FxGsonBuilder. The core and full builder described above 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.

Adding JavaFX support to an existing GsonBuilder

If you cannot (or don't want to) let FX Gson create your GsonBuilder, you may still add JavaFX Properties support to an existing one with this nice syntax:

GsonBuilder builder = MyLib.getBuilder(); // an existing builder from some external lib
Gson gson = FxGson.addFxSupport(builder).create();

Note that you may still take advantage of the FxGsonBuilder flexibility even with an existing builder, by using the wrapping constructor:

GsonBuilder builder = MyLib.getBuilder(); // an existing builder from some external lib
Gson gson = new FxGsonBuilder(builder).acceptNullPrimitives().create();
Clone this wiki locally