joffrey-bion / fx-gson Goto Github PK
View Code? Open in Web Editor NEWA set of type adapters for Google Gson to make JavaFX properties serialization more natural
License: MIT License
A set of type adapters for Google Gson to make JavaFX properties serialization more natural
License: MIT License
A good amount of users still rely on Java 8, according to multiple 2022 surveys:
So it might be worth publishing a version of this library with bytecode level 8.
When deserializing an italic font, the italic posture information is ignored, and the weight is sometimes ignored as well.
For instance, this font Font.font("Arial", FontWeight.BOLD, FontPosture.ITALIC, 10.0)
is deserialized as regular.
The Font
class does not expose weight and posture independently, but instead exposes an aggregated "style" attribute, which is used in the serialization.
However, weight and posture are specified independently when loading a font via Font.font(family, weight, posture, size)
, which is used during deserialization.
Both the weight and posture should be extracted from the serialized style information.
As it is quite inconvenient for maven users to use JCenter, this project should be uploaded to Maven Central.
In the meantime, I encourage people to use Gradle and notice how nice it is :)
It would be great, if they returned an empty property by default or more flexible: make it configurable.
I currently use this code to get around the issue:
LongProperty myReturn;
if (jsonReader.peek() == JsonToken.NULL) {
jsonReader.nextNull();
myReturn = new SimpleLongProperty();
}
else {
myReturn = new SimpleLongProperty(jsonReader.nextLong());
}
return myReturn;
I am trying to convert a model from JsonObject.
Type type = new TypeToken<Room>() {}.getType();
JsonObject obj = new JsonParser().parse(args[0].toString()).getAsJsonObject();
Gson gson = FxGson.coreBuilder().setPrettyPrinting().disableHtmlEscaping().create();
Room room = gson.fromJson(obj, type);
But I got this error:
javax.persistence.PersistenceException: org.hibernate.InstantiationException: No default constructor for entity: : com.math.pro.ak.model.Room
Then I set this in my class:
public Room() {
this.game = new SimpleStringProperty();
this.mode = new SimpleStringProperty();
this.gameType = new SimpleStringProperty();
this.stake = new SimpleStringProperty();
this.stakeValue = new SimpleFloatProperty();
this.players = new SimpleIntegerProperty();
this.title = new SimpleStringProperty();
this.status = new SimpleStringProperty();
this.buyin = new SimpleFloatProperty();
this.rake = new SimpleFloatProperty();
this.money = new SimpleStringProperty();
}
This dont give me an error but also dont update the table.
I have a class that extends SimpleListProperty<Property>
.
On the serialization, it fails on TypeHelper:
java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
at org.hildan.fxgson.factories.TypeHelper.withRawType(TypeHelper.java:30)
I think the expected behavior should be the one described here: https://stackoverflow.com/questions/21458468/gson-wont-properly-serialise-a-class-that-extends-hashmap
JavaFX Properties are typically initialized like this:
private final StringProperty comment = new SimpleStringProperty(this, "comment");
Unfortunately, FxGson reconstructs JavaFX properties like this:
private final StringProperty comment = new SimpleStringProperty();
thus losing its reference to its owning bean as well as its name.
One of the biggest benefits of including a reference to the bean is that generic listeners can be placed on properties and access the owning bean from within the listener. For me, this renders FxGson unusable, as this is a very common usage of JavaFX. Otherwise, FxGson works very well.
Adding a default out of the box adapter for ObjectProperty<File>
would be handy.
I was getting "java.base does not opens java.io to gson" error.
import java.io.File;
import java.io.IOException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
public class FileAdapter extends TypeAdapter<File>{
@Override
public void write(JsonWriter out, File value) throws IOException {
if(value==null) {
out.nullValue();
return;
}
out.value(value.toString());
}
@Override
public File read(JsonReader in) throws IOException {
if(in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
return new File(in.nextString());
}
}
It is not possible to extend the abstract class PropertyTypeAdapter because it has a package protected constructor.
There is already the crashOnNullPrimitives
option, which allows to choose between an exception or a default value when null is found in place of a primitive value.
We could do the same with null properties: crashOnNullProperties
. For now, null properties are serialized as null without questioning, which is probably not the best behaviour. I belive we should crash by default in this case, and allow special configuration to avoid that crash.
When trying to serialize/deserialize a Property<Font>
or Property<Color>
field, the Gson runs into a StackOverflowError.
It looks like the generic type parameter of Property is not resolved against the whole FxGson factories when searching for the delegate adapter. Therefore, the inner Font or Color inside the property is not (de)serialized using the adapters from JavaFxExtraTypeAdapterFactory
.
Currently there seems to be no release on any of the default maven repositories. Is it located in a different repository or am I doing anything wrong?
Using
Gson fxGson = FxGson.coreBuilder().serializeSpecialFloatingPointValues().create();
does not allow to serialize DoubleProperty(Double.NaN) because we fall in JsonWriter value(double value)
which is not built to take care of NaNs.
However, if I change the write method of DoublePropertyTypeAdapter to:
@Override
public void write(JsonWriter out, DoubleProperty value) throws IOException {
Number nb = value.get();
out.value(nb);
}
it allows us to use JsonWriter value(Number value)
which takes care of this special case.
I didn't test the deserialization and the performance impact yet, but I'd like to have your opinion on this change.
When you have a SimpleListProperty
such as
private final SimpleListProperty<Part> parts = new SimpleListProperty<>(this, "parts", FXCollections.observableArrayList());
there is a problem when deserializing a json object that has a null value:
{
"parts": null,
...
}
You will later get a java.lang.UnsupportedOperationException
exception when trying to add objects to the list. It would be nice if there was an option to simply create an empty list when accepting a null value, that way we wouldn't have to then do a null check on the list's getter.
I'm not sure if this is intentional, but the specified link for the manual download redirects me to a site called jfrog.com. I could only find the jar file for fx-gson on maven.org.
The current implementation of ColorTypeAdapter
uses toString()
to get the hexadecimal string representing the color. This is, as specified in the Javadoc, undocumented behaviour and should not be used as such.
Instead, the actual values for each color should be individually converted to 2-char hexadecimal and concatenated:
int r = (int)Math.round(color.getRed() * 255.0);
int g = (int)Math.round(color.getGreen() * 255.0);
int b = (int)Math.round(color.getBlue() * 255.0);
int o = (int)Math.round(color.getOpacity() * 255.0);
return String.format("#%02x%02x%02x%02x" , r, g, b, o);
really like this library, however I want to use it with an object that extends a JFoenix class (specifically, RecursiveTreeObject). If I try to use it now I get a StackOverflowError. If it eventually supported this I would definitely use it heavily for a very large project. Any chance we could see this functionality added? It's also possible I'm doing it incorrectly, but it works fine serializing with normal Gson.
Hello,
I was really struggling with trying to figure out how to serialize one of my classes into Json that contained a bunch of JavaFX Color objects and saw your answer to a post in StackOverflow linking to your library and the library made it SO SIMPLE ... so ... THANK YOU for writing this library. โบ
When I try to require the libary in my module-info, I get the error: Kotlin: Module org.hildan.fxgson cannot be found in the module graph
It'd be nice to clearly separate API and implementation to avoid unnecessary classpath leaks in the future.
The new Gradle plugin for Java libraries sounds really promising.
JCenter is shutting down on May 1st.
The build should publish to Maven Central directly instead of relying on Bintray's sync.
Would it be possible to get Java-9 modular compatibility? The project has no module-info.java
When deserialize the property object name is empty , but value is correct.
This is needed part for property object. How can we fix this ?
Is there away to add name field, if it is not empty ?
Example code here :
import com.google.gson.Gson;
import javafx.beans.Observable;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import org.hildan.fxgson.FxGson;
import java.io.*;
import java.text.DecimalFormat;
public class AppPreferences {
//public static String separator = ",";
public static String separator = new DecimalFormat("##.##").format(1.5).contains(",") ? ";" : ",";
private static String filePath;
private DoubleProperty commission = new SimpleDoubleProperty(null,"Commission", 0.001);
public AppPreferences(String filePath) {
AppPreferences.filePath = filePath;
}
public void save() throws IOException {
File file = new File(filePath);
if(!file.exists()){
FileHelper.createFile(filePath);
}
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
Gson gson = FxGson.coreBuilder().setPrettyPrinting().disableHtmlEscaping().create();
String json = gson.toJson(this);
byte[] copyBuffer = json.getBytes();
out.write(copyBuffer, 0, copyBuffer.length);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
public AppPreferences fromJson() throws Exception {
File file = new File(filePath);
if(file.exists())
{
FileInputStream inputStream = new FileInputStream(file);
try (BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream)))
{
Gson gson = FxGson.coreBuilder().setPrettyPrinting().disableHtmlEscaping().create();
AppPreferences appPreferences = gson.fromJson(inputReader, AppPreferences.class);
return appPreferences;
} catch (final IOException e) {
e.printStackTrace();
}
}
return new AppPreferences(filePath);
}
public void getVariables(ObservableList<Observable> variables, ObservableMap<ObjectProperty<?>, ObservableList<?>> options){
variables.addAll(commissionProperty());
}
public double getCommission() {
return commission.get();
}
public DoubleProperty commissionProperty() {
return commission;
}
public void setCommission(double commission) {
this.commission.set(commission);
}
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.