When I serialize an array of doubles, I get something like
[16.0,16.0,14.666666666666666,16.22222222222222,15.777777777777779]
In an effort to save bandwidth I implemented a custom serializer that
removes ".0" from integers and keeps 2 decimal digits for numbers
greater than 1.
The result is now the following:
["16","16","14.67","16.22","15.78"]
Almost there, but all numbers have become strings.
I'm stuck here. How to achieve the desired goal?
My code:
NumberFormat doubleFormatter = NumberFormat.getInstance(Locale.US);
doubleFormatter.setMaximumFractionDigits(2);
Gson gson = new GsonBuilder()
.registerTypeAdapter(double.class, new JsonSerializer<Double>() {
public JsonElement serialize(Double value, Type theType,
JsonSerializationContext context) {
String result;
if (value.isInfinite() || value.isNaN() || value.doubleValue()<1)
{
// Small or special values are handled by toString()
result = value.toString();
} else {
// Values greater than 1 are rounded to save bandwidth
result = doubleFormatter.format(value);
}
return new JsonPrimitive(result);
}
}).create();
P.S. someone had a similar problem back in 2008, here:
http://groups.google.com/group/google-gson/browse_thread/thread/51381d16b0bef288/ad09951d165d6cb5?lnk=gst&q=number+formatting#ad09951d165d6cb5