-
-
Save edm00se/095626db6513c4bf01cadeff92935094 to your computer and use it in GitHub Desktop.
Customizing GSON for less science-y Double value handling
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
... | |
/** | |
* @return String -ified (JSON) version of Object ob, via GSON | |
*/ | |
public static getSomeJsonStr(Object ob){ | |
... | |
Gson g = new Gson(); | |
return g.toString(ob); | |
} | |
... |
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
... | |
/** | |
* @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); | |
} | |
... |
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
... | |
/** | |
* 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