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

Preprocessor for Array Insertion #38

Closed ManueGE closed 6 years ago

ManueGE commented 6 years ago

May it possible adding a preprocessor/postprocessor to make some changes before/after inserting an array of objects?

I mean, something like this:

public class ArrayPreProcessor implements PreProcessor<List<MyClass>> {

    @Override
    public void preDeserialize(Class<? extends List<MyClass>> clazz, JsonElement src, Gson gson) {
         // whatever
    }

Any chance to be added in the future?

julman99 commented 6 years ago

Hello,

I don't seem to understand correctly the request. Can you give a more concrete example?

Thanks

ManueGE commented 6 years ago

Sure, let's suppose we have a class User (with id and name). I got this JSON:

[
   {"id": 1, "name": "John"},
   {"id": 2, "name": "Mary"},
   {"id": 3, "name": "Michael"}
]

I can write a PreProcessor/PostProcessor to intercept each one of the jsons within the array before/after convert them to Users, but I would like to have one PreProcessor to intercept the full JSON array at once.

Does it makes more sense?

julman99 commented 6 years ago

Oh ok, got it now.

I think the way to do this is to add a new feature to the GsonFireBuilder to allow registering processors to a TypeToken.

So you would do:

gsonFireBuilder.registerPreProcessor(new TypeToken<List<user>>(){}.getType(), /* here the preprocessor */);

I'll play with that approach during the weekend and give you an update here

ManueGE commented 6 years ago

That would be awesome. Thanks :)

julman99 commented 6 years ago

I think I found a ~not so pretty~ way to make it work:

Try this:

gsonFireBuilder.registerPreProcessor((Class<List<User>>)new TypeToken<List<User>>(){}.getRawType(), /* here the preprocessor for List<User>*/);
ManueGE commented 6 years ago

Thanks you very much. I'll give it a try :)

You can close the issue.