I use gson both for serializing and deserializing java objects as well as its built-in JsonElement. If I'm serializing a java object then I can register a type adapter and it will get called and allow me to provide a custom serialization.
But when I have a JsonElement, I can't seem to get it to ever recognize the type I want to adapt. Say I have this:
JsonArray arr = new JsonArray();
arr.add(Math.PI);
arr.add(Math.E);
System.out.println(arr.toString());
This will print out:
[3.141592653589793,2.718281828459045]
But how do I limit this to, say, three fractional digits? I was hoping I could add a type adapter, but I can't get anything to ever register, i.e., the adapter's methods are never called. Am I supposed to register a Double, Number, JsonPrimitive, or something else in this case? I've tried them all and nothing works.
And even if it did work, I think the best I could do is some math rounding, because if I tried to 'adapt' the number using, say, String.format()
then the result would be a string and not a number, and I want the output json to remain a number.
Or maybe I'm completely missing something? Here's one example of what I've tried:
Gson gson = (new GsonBuilder()).registerTypeAdapter(
JsonPrimitive.class,
new TypeAdapter<JsonPrimitive>() {
@Override
public JsonPrimitive read(JsonReader reader) throws IOException {
// never using deserialization, don't expect this to print
System.out.println("read adapter");
return null;
}
@Override
public void write(JsonWriter writer, JsonPrimitive primitive) throws IOException {
// this never gets called; output same as above
System.out.println("write adapter");
writer.nullValue();
}
}
).create();
System.out.println(gson.toJson(arr));