How to serialize Optional classes with Gson?

后端 未结 5 2189
囚心锁ツ
囚心锁ツ 2020-12-15 05:47

I have an object with the following attributes.

private final String messageBundle;
private final List messageParams;
private final String acti         


        
5条回答
  •  不知归路
    2020-12-15 06:15

    After several hours of gooling and coding - there is my version:

    public class OptionalTypeAdapter extends TypeAdapter> {
    
        public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
            @Override
            public  TypeAdapter create(Gson gson, TypeToken type) {
                Class rawType = (Class) type.getRawType();
                if (rawType != Optional.class) {
                    return null;
                }
                final ParameterizedType parameterizedType = (ParameterizedType) type.getType();
                final Type actualType = parameterizedType.getActualTypeArguments()[0];
                final TypeAdapter adapter = gson.getAdapter(TypeToken.get(actualType));
                return new OptionalTypeAdapter(adapter);
            }
        };
        private final TypeAdapter adapter;
    
        public OptionalTypeAdapter(TypeAdapter adapter) {
    
            this.adapter = adapter;
        }
    
        @Override
        public void write(JsonWriter out, Optional value) throws IOException {
            if(value.isPresent()){
                adapter.write(out, value.get());
            } else {
                out.nullValue();
            }
        }
    
        @Override
        public Optional read(JsonReader in) throws IOException {
            final JsonToken peek = in.peek();
            if(peek != JsonToken.NULL){
                return Optional.ofNullable(adapter.read(in));
            }
    
            in.nextNull();
            return Optional.empty();
        }
    
    }
    

    You can simple registered it with GsonBuilder like this:

    instance.registerTypeAdapterFactory(OptionalTypeAdapter.FACTORY)
    

    Please keep attention that Gson does not set values to your class field if field does not present in json. So you need to set default value Optional.empty() in your entity.

提交回复
热议问题