Skip to content

Basic FX Gson usage

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

You can use FX Gson in multiple ways depending on the degree of customization you need. Here is how.

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.

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