为什么数字会自动加倍? [英] Why is a number casted automatically to double?
问题描述
我为我的webservice使用spring启动。每个方法返回 Map< Object,Object>
,因为它是一个通用类型,并且方法能够返回任何响应,原始 int
或复杂的自定义对象
User
。另外,我使用 Map< Object,Object>
来消除JSON中的反斜杠\,而不是使用String。
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.
但是我在客户端(Android应用程序)中有变量转换的问题。
But I got problem with variable casting in client (Android app).
Map中的数字变量自动转换为double(1.0,2.0,3.0,5.0, ..),而在服务器中 long
。
Number variables in Map are automatically casted to double (1.0, 2.0, 3.0, 5.0, ...) while it is long
in server.
如果我在服务器上将数字转换为字符串,客户是正确的例如1,2,3,5,...
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())
服务器端变量:
long id;
服务器端方法:
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代码。改造
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();
}
});
推荐答案
JSON是一个JavaScript对象。在javascript中,没有longs或float或double。一切都是一个数字,它都在后台使用双。所以当你发送JSON,除非你告诉它解释一个值为一个明确的长度,它必须假设它可以是任何有效的数字 - 它必须假设一个双。
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.
这篇关于为什么数字会自动加倍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!