Gson has a limitation in that you cannot register a TypeAdapter for
Number.class. You can, however, extend Number with your own class and
write a TypeAdapter for that. Here's an example:
DoubleOrInt.java
===============
import com.google.gson.*;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Arrays;
public class DoubleOrInt extends Number {
private Number number;
public DoubleOrInt(Number n) {
number = n;
}
@Override
public double doubleValue() {
return number.doubleValue();
}
@Override
public float floatValue() {
return number.floatValue();
}
@Override
public int intValue() {
return number.intValue();
}
@Override
public long longValue() {
return number.longValue();
}
public Class<? extends Number> getNumberClass() {
return number.getClass();
}
@Override
public String toString() {
return number.toString();
}
public static class Adapter extends TypeAdapter<DoubleOrInt> {
@Override
public DoubleOrInt read(JsonReader jReader) throws IOException {
String json = jReader.nextString();
Number n;
if (json.indexOf('.') < 0) {
n = Integer.valueOf(json);
} else {
n = Double.valueOf(json);
}
return new DoubleOrInt(n);
}
@Override
public void write(JsonWriter out, DoubleOrInt value) throws
IOException {
out.value(value);
}
}
public static void main(String[] args) {
Gson gson = new
GsonBuilder().registerTypeAdapter(DoubleOrInt.class, new
Adapter()).create();
for (String json: Arrays.asList("42", "3.14")) {
DoubleOrInt n = gson.fromJson(json, DoubleOrInt.class);
System.out.println(n.getNumberClass().getName() + " with
value " + n.toString());
}
}
}
===============
java -cp .:gson-2.2.2.jar DoubleOrInt
java.lang.Integer with value 42
java.lang.Double with value 3.14
> --
> You received this message because you are subscribed to the Google Groups
> "google-gson" group.
> To view this discussion on the web visit
>
https://groups.google.com/d/msg/google-gson/-/ptVQJxTEpe0J.
> To post to this group, send email to
googl...@googlegroups.com.
> To unsubscribe from this group, send email to
>
google-gson...@googlegroups.com.
> For more options, visit this group at
>
http://groups.google.com/group/google-gson?hl=en.