How to serialize Optional classes with Gson?

后端 未结 5 2183
囚心锁ツ
囚心锁ツ 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:22

    The solution by Ilya ignores type parameters, so it can't really work in the general case. My solution is rather complicated, because of the need to distinguish between null and Optional.absent() -- otherwise you could strip away the encapsulation as a list.

    public class GsonOptionalDeserializer
    implements JsonSerializer>, JsonDeserializer> {
    
        @Override
        public Optional deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            final JsonArray asJsonArray = json.getAsJsonArray();
            final JsonElement jsonElement = asJsonArray.get(0);
            final T value = context.deserialize(jsonElement, ((ParameterizedType) typeOfT).getActualTypeArguments()[0]);
            return Optional.fromNullable(value);
        }
    
        @Override
        public JsonElement serialize(Optional src, Type typeOfSrc, JsonSerializationContext context) {
            final JsonElement element = context.serialize(src.orNull());
            final JsonArray result = new JsonArray();
            result.add(element);
            return result;
        }
    }
    

提交回复
热议问题