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

Use custom deserialization after registerTypeSelector #14

Closed horte closed 9 years ago

horte commented 9 years ago

Firstly, thx for a great add-on to gson!

I am using registerTypeSelector to find the type when doing deserializations and it works as expected. Though, my json looks like below and I only want to select the event field when doing the actual deserialization to an object. How would i approach this? I tried using registerPreProcessor and alter the src like src = src.getAsJsonObject().getAsJsonObject("event"); but it doesn't seam to work. Is there a way to actually do this or is it outside of the gson-fire scope?

{
  "event" : { "id": 1, "name": "Fredrik"},
  "type" : "UserCreatedEvent"
}

Thanks!

julman99 commented 9 years ago

Hello there,

This: src = src.getAsJsonObject().getAsJsonObject("event"); won't work since you are changing the reference of the variable only the context of the method.

On Gson-Fire 2.0 I was planning to allow the pre and post processors to return a modified version of object, but for now the only way is to mutate the object passed in the method. It looks hacky, but you might want to try something like this:

JsonObject container = src.getAsJsonObject();
JsonObject event = container.getAsJsonObject("event");

container.remove("event");
container.remove("type");

//full copy of the event object to the parent
for(Map.Entry<String, JsonElement> entries: event.entrySet()) {
    container.add(entries.getKey(), entries.getValue());    
}

Let me know if it works.

horte commented 9 years ago

Thank you for the quick reply. It looks like that would work, though in this particular case I actually ended up doing like this without using regiserTypeSelector

JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse((String) serialized).getAsJsonObject();
JsonObject jsonEvent = jsonObject.getAsJsonObject("event");
String type = jsonObject.getAsJsonPrimitive("type").getAsString();

Event e = (Event) gson.fromJson(jsonEvent, getClazz(type));

Whereas getClazz checks the type to return.