Чечил Крым
Чечил Крым

Reputation: 309

Why is a number casted automatically to double?

I use spring boot for my webservice. Each method returns Map<Object, Object> because it is a general type and the methods are able to return any response, either a primitive int or complex custom object of User. Also I used Map<Object, Object> to eliminate backslash "\" in JSON, instead of using String.

But I got problem with variable casting in client (Android app).

Number variables in Map are automatically casted to double (1.0, 2.0, 3.0, 5.0, ...) while it is long in server.

If I cast number to string at server, then casting at client is right e.g. 1, 2, 3, 5, ...

return String.valueOf(u.getId())

Server side variable:

long id;

Server side method:

public final static String SUCCESS = "0";
public final static String NOT_FOUND = "-1";

Map<Object, Object> m = new HashMap<>();

@RequestMapping("/getUser")
Map<Object, Object> getUser(@RequestParam(value = "phoneNumber", defaultValue = "") String phoneNumber,
        @RequestParam(value = "hash", defaultValue = "") String hash) {

    m.clear();

    User user = userRepository.findByPhoneNumberAndHash(phoneNumber, hash);
    if (user != null) {
        m.put(ERROR_JSON, SUCCESS);
        m.put(VALUE_JSON, user);
    } else {
        m.put(ERROR_JSON, NOT_FOUND);
    }
    return m;
}

JSON:

[{"id":1}] and [{"id":"1"}]

Android code. Retrofit

userService.getUser(phoneNumber, hash).enqueue(new Callback<Map<Object, Object>>() {

    @Override
    public void onResponse(Call<Map<Object, Object>> call, Response<Map<Object, Object>> response) {
        Map<Object, Object> m = response.body();
    }
    @Override
    public void onFailure(Call<Map<Object, Object>> call, Throwable t) {
        t.printStackTrace();
    }
});

enter image description here

Upvotes: 0

Views: 308

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93668

JSON is a JavaScript Object. In javascript, there are no longs or floats or doubles. Everything is a number, and it all uses double in the background. So when you send JSON, unless you tell it to interpret a value as a long explicitly, it has to assume it could be any valid number- it has to assume its a double.

Upvotes: 1

Related Questions