Skip to content

Instantly share code, notes, and snippets.

@edm00se
Last active Jan 17, 2017
Embed
What would you like to do?
Customizing GSON for less science-y Double value handling
...
/**
* @return String -ified (JSON) version of Object ob, via GSON
*/
public static getSomeJsonStr(Object ob){
...
Gson g = new Gson();
return g.toString(ob);
}
...
...
/**
* @return String -ified (JSON) version of Object ob, via custom GSON instance
*/
public static getSomeJsonStr(Object ob){
...
Gson g = Utils.getCustomGsonInstance();
return g.toString(ob);
}
...
...
/**
* Makes use of a custom type adapter to convert Double values without
* using scientific notation.
*
* @return Gson instance with custom handling of Double values
*/
public static String getCustomGsonInstance() {
GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
public JsonElement serialize(final Double src, final Type typeOfSrc, final JsonSerializationContext context) {
BigDecimal value = BigDecimal.valueOf(src);
return new JsonPrimitive(value);
}
});
Gson g = gb.create();
return g;
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment