julman99 / gson-fire

A java library that adds some very useful features to Gson, like Date serializing to unix timestamp or RFC3339, method (getters) serialization, pre/post processors and many others. Check out the documentation to learn how to use it!
http://gsonfire.io
Other
229 stars 37 forks source link

Custom deserialization without deserializer/type adapter? #36

Open piegamesde opened 7 years ago

piegamesde commented 7 years ago

I got a lot of smaller classes that need custom (de)serialization logic. And I don't want to create a Type Adapter class for each of them, especially because this would require registering the adapter for the class and not all classes are known at runtime.

So I'd like to have something like:

public class MyData {
    private int dataField = 10;

    // @Annotation?
    private void writeJsonObject(/* args */) {
        // Custom logic here
    }

    // @Annotation?
    private void readJsonObject(/* args */) {
        // Custom logic here
    }
}

Both of the methods should be recognized and called automatically for the serialization without the need of registering it to the Gson object. Is something like this possible?

julman99 commented 7 years ago

Currently, there is not explicit way of doing this (or at least to my knowledge). You could serialize/deserialize your object with the standard Gson/GsonFire features and use in conjunction the @PreSerialize and @PostDeserialize hooks in your class that Gson on Fire will invoke.

If that doesn't work for you I could consider implementing a "self serializable" annotation, or something like that

piegamesde commented 7 years ago

Yes, I was looking for some "custom self serialization" (I just did not know how to put it). I have not used hooks yet and I don't really know how to do actual (de)serialization work with them, since they don't take any JSON stuff in the arguments.

If that doesn't work for you I could consider implementing a "self serializable" annotation, or something like that

That would come in really handy. But I can't judge how complex this is to implement.

julman99 commented 7 years ago

Regarding the post deserialize hook, you can add a Gson and a JsonElement argument to your method and GsonFire will properly inject them

I will evaluate if the self serialization object makes sense as part of GsonFire and come back with an answer in the next two days wether it will make it or not into the library.