julman99/gson-fire

Access to JsonElement in @PostDeserialize

molexx opened this issue · 5 comments

It seems that @PostDeserialize'd methods need to have 0 arguments. Is there a way to access the source JsonElement from within the method?

If not, could it be added as an argument please?

This would be useful when the JSON contains keys that do not have matching property names in the class.

I'd be happy to submit a pull request with changes to FireTypeAdapter.java and HooksInvoker.java if that makes sense.

Hello, I'll evaluate adding that feature (automatically inject a JsonElement if specified as a parameter on the method). However, I suggest using GsonFireBuilder.registerPostProcessor since it is more flexible and decouples the post processing logic from the models. You can still have a static class inside your model to handle private fields, for example

public class MyModel {
    private String name;
    private String nameLowercase;

    public static class MyModelPostProcessor implements PostProcessor<MyModel> {

        void postDeserialize(MyModel result, JsonElement src, Gson gson) {
            result.nameLowercase = result.name.toLowerCase();
        }

        void postSerialize(JsonElement result, MyModel src, Gson gson) {
            //nothing
        }
    }
}

// In the code you initialize GsonFire
new GsonFireBuilder()
  .registerPostProcessor(MyModel.class, new MyModel.MyModelPostProcessor())

Sorry if the code above does not compiles, I did it in a plain text editor.

Let me know if that fixes your issue

The PostProcessor would do it but the @PostDeserialize annotation makes more concise and tidier code. The boilerplate of the PostProcessor static class can be skipped and it's simpler to setup the builder by calling .enableHooks() than .registerPostProcessor() because you only need to mention the Model.class, not the PostProcessor too.

(I intend to dynamically generate the calls to .enableHooks() so I don't need to manually list out all the Model classes)

Clearer and simpler code is the reason I'm attracted to gson-fire on top of standard GSON. Thanks BTW :-)

Hello, this enhancement was just added in 1.5.0

Let me know if it works for you. Thanks!

Hi, yes works great for me, thanks!

Nice!