Created
October 15, 2015 16:49
-
-
Save x4d3/b0f397347f41e893f5fd to your computer and use it in GitHub Desktop.
a proposition of a DtoJsonStringHelper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DtoJsonStringHelper { | |
private DtoJsonStringHelper() { | |
} | |
private static final Gson GSON = new GsonBuilder() | |
.registerTypeAdapter(Optional.class, new GsonOptionalDeserializer()) | |
.registerTypeAdapter(List.class, new GsonListDeserializer()) | |
.create(); | |
private static class GsonOptionalDeserializer implements JsonSerializer<Optional<?>> { | |
@Override | |
public JsonElement serialize(Optional<?> src, Type typeOfSrc, JsonSerializationContext context) { | |
final JsonElement element = context.serialize(src.toString()); | |
final JsonArray result = new JsonArray(); | |
result.add(element); | |
return result; | |
} | |
} | |
private static class GsonListDeserializer implements JsonSerializer<List<?>> { | |
@Override | |
public JsonElement serialize(List<?> src, Type typeOfSrc, JsonSerializationContext context) { | |
String value; | |
if (src.size() > 1000){ | |
value = "trop long"; | |
}else{ | |
value = src.toString(); | |
} | |
final JsonElement element = context.serialize(value); | |
final JsonArray result = new JsonArray(); | |
result.add(element); | |
return result; | |
} | |
} | |
public static String toString(Object o) { | |
Preconditions.checkNotNull(o); | |
return o.getClass().getSimpleName() + GSON.toJson(o); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment