Skip to content

Built in GsonBuilders

Joffrey Bion edited this page Oct 28, 2016 · 11 revisions

There are currently 2 built-in GsonBuilders in FX Gson: the core builder and the full builder.

Core builder

This GsonBuilder is pre-setup with the JavaFxPropertyTypeAdapterFactory able to handle the following types:

  • BooleanProperty
  • IntegerProperty
  • LongProperty
  • FloatProperty
  • DoubleProperty
  • StringProperty
  • ListProperty
  • SetProperty
  • MapProperty
  • Property<T> (including ObjectProperty)

And a few InstanceCreators to handle observable collections:

  • ObservableList
  • ObservableMap
  • ObservableSet

Deserialization

The deserialization of the properties' values is done by creating a "Simple" property of the relevant type. For instance, the integer 5 will be deserialized as a new SimpleIntegerProperty(5).

Observable collections are deserialized using the more standard implementation:

  • ObservableList is deserialized as FXCollections.observableArrayList()
  • ObservableMap is deserialized as FXCollections.observableHashMap()
  • ObservableSet is deserialized as FXCollections.observableSet() (internally uses a HashSet)

If need be, you may override these implementations by registering your own adapters.

Null handling

Gson doesn't call TypeAdapters if it does not encounter the corresponding field value in the serialized JSON. In order to properly deserialize null values into properties, the serializeNulls() configuration is also applied on the core GsonBuilder. This is because non-null properties containing a null value would otherwise be deserialized as null properties which makes the serialization asymmetric.

If you don't care about symmetry or if you're just interested in serialization (and never deserialize), then you may avoid this by manually creating your GsonBuilder and registering FX Gson type adapters.

Full builder

This GsonBuilder is pre-setup with the same factory as the core builder, plus the JavaFxExtraTypeAdapterFactory able to handle the following types:

Class Serialized with FX Gson Original serialization
javafx.scene.paint.Color '#' + RGBA hexadecimal representation Complex structure with nested object
javafx.scene.text.Font The string "Family,Weight,Size" StackOverflowException (too deep)

Examples:

  • Color.RED is serialized as #ff0000ff
  • The standard Arial font in 11pt is serialized as "Arial,Regular,11.0"
  • The Sans Serif font in 14pt bold gives "SansSerif,Bold,14.0"
Clone this wiki locally