Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implicit typecasting #2210

Closed
Faisal-Alsumait opened this issue Sep 30, 2022 · 1 comment
Closed

implicit typecasting #2210

Faisal-Alsumait opened this issue Sep 30, 2022 · 1 comment
Labels

Comments

@Faisal-Alsumait
Copy link

Gson version

2.9.1

Java

java 15.0.1

Used tools

Maven 3.8.1

Description

When mapping String to Object using fromJson method, wrong implicit typecasting was performed

Expected behavior

correct implicit typecasting .

Actual behavior

wrong implicit typecasting .

Reproduction steps

        Gson gson = new Gson();
        String integerNumber = "9";
        String longNumber = "999999999999";
        Object integerValue = gson.fromJson(integerNumber, Object.class);
        Object longValue = gson.fromJson(longNumber, Object.class);
        System.out.println(integerValue.getClass()); //  Expected behavior: class java.lang.Integer, Actual behavior: class java.lang.Double
        System.out.println(longValue.getClass()); //  Expected behavior: class java.lang.Long, Actual behavior: class java.lang.Double
@Marcono1234
Copy link
Collaborator

This is intended. For backward compatibility when Gson is told to deserialize Object.class and encounters a JSON number it will by default always deserialize it as Double.

To account for use cases where this is not desired Gson provides a ToNumberStrategy which allows customizing this behavior. Gson has some built-in strategies provided by ToNumberPolicy, but none of those seems to be what you are looking for. Though you can implement your own in a similar way to how LONG_OR_DOUBLE is implemented:

@Override public Number readNumber(JsonReader in) throws IOException, JsonParseException {
String value = in.nextString();
try {
return Long.parseLong(value);
} catch (NumberFormatException longE) {
try {
Double d = Double.valueOf(value);
if ((d.isInfinite() || d.isNaN()) && !in.isLenient()) {
throw new MalformedJsonException("JSON forbids NaN and infinities: " + d + "; at path " + in.getPreviousPath());
}
return d;
} catch (NumberFormatException doubleE) {
throw new JsonParseException("Cannot parse " + value + "; at path " + in.getPreviousPath(), doubleE);
}
}
}

See also #1290 which added this feature and contains some more background information about this feature.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants