-
-
Notifications
You must be signed in to change notification settings - Fork 5
Basic FX Gson usage
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();
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.
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 NullPrimitiveException
s 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.
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();