I need to convert json string to java object and display it as a long. The json string is a fixed array of long numbers:
{numbers
[ 268627104, 485677888, 506
I had a similar problem, and it not only converts integers to double, but it actually loses precision for certain long numbers, as described in this related question.
I tracked down this conversion to ObjectTypeAdapter
's read
method, specifically:
case NUMBER:
return in.nextDouble();
It may be possible to plug in a modified TypeAdapter
for Object
, but I couldn't get that to work, so instead I just copied the read
method (Object read(JsonReader in)
) to my own code and modified the above lines to this:
case NUMBER:
final String s = in.nextString();
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
// ignore
}
try {
return Long.parseLong(s);
} catch (NumberFormatException e) {
// ignore
}
return Double.parseDouble(s);
I wish Gson did this by default..
Then I put the other connecting pieces in a helper method that looks something like this:
public static Object parse(final Reader r) {
try (final JsonReader jr = new JsonReader(r)) {
jr.setLenient(true);
boolean empty = true;
Object o = null;
try {
jr.peek();
empty = false;
o = read(jr);
} catch (EOFException e) {
if (!empty) {
throw new JsonSyntaxException(e);
}
}
if (o != null && jr.peek() != JsonToken.END_DOCUMENT) {
throw new JsonIOException("JSON document was not fully consumed.");
}
return o;
} catch (IOException e) {
throw new JsonIOException(e);
}
}
So now instead of new Gson().fromJson(r, Object.class)
, I call parse(r)
.
This works well for me because I want to be able to parse json data with any structure, but if you have a particular class you're targeting, you probably just need to eliminate occurrences of Object
within that class's members.