Skip to content

Instantly share code, notes, and snippets.

@edm00se
Last active January 17, 2017 04:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edm00se/095626db6513c4bf01cadeff92935094 to your computer and use it in GitHub Desktop.
Save edm00se/095626db6513c4bf01cadeff92935094 to your computer and use it in GitHub Desktop.
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