yes it is possible and you can do it by following these steps.You need to register a GSON type adapter to perform a custom serialization and deserialization of the property:first create StringPropertyAdapter.java
import com.google.gson.*;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import java.lang.reflect.Type;
public class StringPropertyAdapter implements
JsonSerializer<StringProperty>,
JsonDeserializer<StringProperty> {
@Override
public JsonElement serialize(
StringProperty property,
Type type,
JsonSerializationContext jsonSerializationContext
) {
return new JsonPrimitive(
property.getValue()
);
}
@Override
public StringProperty deserialize(
JsonElement json,
Type type,
JsonDeserializationContext jsonDeserializationContext
) throws JsonParseException {
return new SimpleStringProperty(
json.getAsJsonPrimitive().getAsString()
);
}
}
then create main in PropertySerializationTest.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javafx.beans.property.StringProperty;
public class PropertySerializationTest {
public static void main(String[] args) {
final DatabaseEntry entry = new DatabaseEntry("toolhouse", 18, 16, "Property");
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(StringProperty.class, new StringPropertyAdapter());
final Gson gson = gsonBuilder.create();
System.out.println("Serialized Data:");
String json = gson.toJson(entry);
System.out.println(json);
System.out.println("De-serialized/Re-serialized Data:");
DatabaseEntry rebuiltEntry = gson.fromJson(json, DatabaseEntry.class);
String rebuiltJson = gson.toJson(rebuiltEntry);
System.out.println(rebuiltJson);
}
}
our data entry class,DatabaseEntry.java
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class DatabaseEntry {
private String companyName;
private int _id;
private int employees;
private StringProperty testString = new SimpleStringProperty();
public DatabaseEntry(String companyName, int employees, int _id, String test) {
this.companyName = companyName;
this.employees = employees;
this._id = _id;
this.testString.setValue(test);
}
}
when you run the PropertySerializationTest.java then you will get this output:
Serialized Data:
{"companyName":"toolhouse","_id":16,"employees":18,"testString":"Property"}
De-serialized/Re-serialized Data:
{"companyName":"toolhouse","_id":16,"employees":18,"testString":"Property"}
Reference: http://stackoverflow.com/questions/36046679/saving-javafx-properties-in-mongodb