简体   繁体   English

为什么数字会自动转换为双倍?

[英]Why is a number casted automatically to double?

I use spring boot for my webservice. 我将spring boot用于我的Web服务。 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 . 每个方法都返回Map<Object, Object>因为它是通用类型,并且这些方法能够返回任何响应,无论是原始int还是User复杂自定义对象。 Also I used Map<Object, Object> to eliminate backslash "\\" in JSON, instead of using String. 我还使用Map<Object, Object>在JSON中消除了反斜杠“ \\”,而不是使用String。

But I got problem with variable casting in client (Android app). 但是我在客户端(Android应用)中进行变量强制转换时遇到问题。

Number variables in Map are automatically casted to double (1.0, 2.0, 3.0, 5.0, ...) while it is long in server. 服务器中long Map中的数字变量会自动转换为双精度(1.0、2.0、3.0、5.0等)。

If I cast number to string at server, then casting at client is right eg 1, 2, 3, 5, ... 如果我在服务器上将数字转换为字符串,则在客户端进行转换是正确的,例如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: JSON:

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

Android code. Android代码。 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();
    }
});

在此处输入图片说明

JSON is a JavaScript Object. JSON是JavaScript对象。 In javascript, there are no longs or floats or doubles. 在javascript中,没有long或float或double。 Everything is a number, and it all uses double in the background. 一切都是数字,并且在后台都使用double。 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. 因此,当您发送JSON时,除非您告诉它明确地将一个值解释为long值,否则它必须假定它可以是任何有效数字-它必须假定它是一个double。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM