I have an object with the following attributes.
private final String messageBundle;
private final List messageParams;
private final String acti
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;
}
}