Giter Site home page Giter Site logo

joffrey-bion / fx-gson Goto Github PK

View Code? Open in Web Editor NEW
53.0 5.0 5.0 488 KB

A set of type adapters for Google Gson to make JavaFX properties serialization more natural

License: MIT License

Java 100.00%
gson javafx fx-gson json serialize-javafx-properties

fx-gson's People

Contributors

antoine-guillou avatar dependabot[bot] avatar glavo avatar joffrey-bion avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

fx-gson's Issues

Incorrect serialization/deserialization of italic fonts

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.

Cause

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.

Deploy to maven central

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 :)

PropertyCreators return null if the json value of the property is null.

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;

gson.fromJson

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.

Cannot serialize custom property class extending a generic property type

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 Lose Meta-Data

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.

ObjectProperty<File>

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());		
	}

}

Add option for null properties serialization

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.

Property<Font> crashes serialization

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.

Can't fetch project via maven.

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?

Serialize DoubleProperty of NaN

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.

SimpleListProperty becomes unmodifiable when deserializing a null value.

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.

ColorTypeAdapter should not rely on Color.toString()

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);

Cannot use this library alongside JFoenix extended POJO's

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.

Just a Thank You

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. โ˜บ

Use Java-library Gradle plugin

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.

Property object name is empty

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);
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.