Is possible to use setters when Gson deserializes a JSON?

后端 未结 2 2074
渐次进展
渐次进展 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 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 {
    
        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())
    

提交回复
热议问题