Is possible to use setters when Gson deserializes a JSON?

后端 未结 2 2054
渐次进展
渐次进展 2021-01-04 13:17

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

相关标签:
2条回答
  • 2021-01-04 13:43

    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())
    
    0 讨论(0)
  • 2021-01-04 13:51

    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.

    0 讨论(0)
提交回复
热议问题