Make the BigDecimal and BigInteger type adapters user-overrideable.

This commit is contained in:
Jesse Wilson 2012-03-18 17:55:15 +00:00
parent 5e3f5a6bbe
commit 9be0fd9ecc
2 changed files with 36 additions and 2 deletions

View File

@ -211,8 +211,6 @@ public final class Gson {
factories.add(TypeAdapters.CHARACTER_FACTORY);
factories.add(TypeAdapters.STRING_BUILDER_FACTORY);
factories.add(TypeAdapters.STRING_BUFFER_FACTORY);
factories.add(TypeAdapters.newFactory(BigDecimal.class, TypeAdapters.BIG_DECIMAL));
factories.add(TypeAdapters.newFactory(BigInteger.class, TypeAdapters.BIG_INTEGER));
factories.add(TypeAdapters.JSON_ELEMENT_FACTORY);
factories.add(ObjectTypeAdapter.FACTORY);
@ -220,6 +218,8 @@ public final class Gson {
factories.addAll(typeAdapterFactories);
// built-in type adapters that can be overridden
factories.add(TypeAdapters.newFactory(BigDecimal.class, TypeAdapters.BIG_DECIMAL));
factories.add(TypeAdapters.newFactory(BigInteger.class, TypeAdapters.BIG_INTEGER));
factories.add(new CollectionTypeAdapterFactory(constructorConstructor));
factories.add(TypeAdapters.URL_FACTORY);
factories.add(TypeAdapters.URI_FACTORY);

View File

@ -16,6 +16,7 @@
package com.google.gson.functional;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
@ -266,6 +267,22 @@ public class DefaultTypeAdaptersTest extends TestCase {
ClassWithBigInteger actual = gson.fromJson(json, ClassWithBigInteger.class);
assertEquals(expected.value, actual.value);
}
public void testOverrideBigIntegerTypeAdapter() throws Exception {
gson = new GsonBuilder()
.registerTypeAdapter(BigInteger.class, new NumberAsStringAdapter(BigInteger.class))
.create();
assertEquals("\"123\"", gson.toJson(new BigInteger("123"), BigInteger.class));
assertEquals(new BigInteger("123"), gson.fromJson("\"123\"", BigInteger.class));
}
public void testOverrideBigDecimalTypeAdapter() throws Exception {
gson = new GsonBuilder()
.registerTypeAdapter(BigDecimal.class, new NumberAsStringAdapter(BigDecimal.class))
.create();
assertEquals("\"1.1\"", gson.toJson(new BigDecimal("1.1"), BigDecimal.class));
assertEquals(new BigDecimal("1.1"), gson.fromJson("\"1.1\"", BigDecimal.class));
}
public void testSetSerialization() throws Exception {
Gson gson = new Gson();
@ -674,4 +691,21 @@ public class DefaultTypeAdaptersTest extends TestCase {
}
}
}
static class NumberAsStringAdapter extends TypeAdapter<Number> {
private final Constructor<? extends Number> constructor;
NumberAsStringAdapter(Class<? extends Number> type) throws Exception {
this.constructor = type.getConstructor(String.class);
}
@Override public void write(JsonWriter out, Number value) throws IOException {
out.value(value.toString());
}
@Override public Number read(JsonReader in) throws IOException {
try {
return constructor.newInstance(in.nextString());
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
}