13

Is there any way the set methods of a given class, are used when using Gson's fromJson method?

I would like to do this because for every String global variable of the target class a trim is made.

Is there any GSON API annotation for this?

I am aware that GSON provides the ability to write custom serializers/deserializers but I would like to know if there is another way to achieve this.

giampaolo
  • 6,906
  • 5
  • 45
  • 73
RedEagle
  • 4,418
  • 9
  • 41
  • 64

2 Answers2

16

No, there is not. Gson works mainly by reflection on instance fields. So if you do not plan to move to Jackson that has this feature I think you cannot have a general way to call your setters. So there's no annotation for that.

BUT

to achieve your specific need you could:

  1. write your own custom TypeAdapter or
  2. create a constructor that has the string you intend to trim and create a custom InstanceCreator or
  3. parse your JSON as JsonObject, do some processing of the strings and then use that object as source for parsing into your class.

I can provide you with more hints as long as you post some code or give information about your data/JSON.

TarikW
  • 359
  • 4
  • 12
giampaolo
  • 6,906
  • 5
  • 45
  • 73
4

I implemented a JsonDeserializer<String> and registered it on GsonBuilder. So, to all String fields received, Gson will use my StringGsonTypeAdapter to deserialize the value.

Below is my code:

import static net.hugonardo.java.commons.text.StringUtils.normalizeSpace;
import static net.hugonardo.java.commons.text.StringUtils.trimToNull;

final class StringGsonTypeAdapter implements JsonDeserializer<String> {

    private static final StringGsonTypeAdapter INSTANCE = new StringGsonTypeAdapter();

    static StringGsonTypeAdapter instance() {
        return INSTANCE;
    }

    @Override
    public String deserialize(JsonElement jsonElement, Type type, 
        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        return normalizeSpace(trimToNull(jsonElement.getAsString()));
    }
}

...and my GsonBuilder:

Gson gson = new GsonBuilder()
    .registerTypeAdapter(String.class, StringGsonTypeAdapter.instance())
    .create())
hugonardo
  • 337
  • 2
  • 9