为什么一个数字会自动翻倍加倍?

时间:2016-09-29 14:29:00

标签: java android json casting

我使用spring boot作为我的webservice。每个方法都返回Map<Object, Object>,因为它是一般类型,并且方法能够返回任何响应,原始intUser的复杂自定义对象。我还使用Map<Object, Object>来消除JSON中的反斜杠“\”,而不是使用String。

但是我在客户端(Android应用程序)中遇到变量转换问题。

Map中的数字变量会在服务器中long时自动转换为double(1.0,2.0,3.0,5.0,...)。

如果我将数字转换为服务器上的字符串,那么在客户端进行转换是正确的,例如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代码。改型

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

1 个答案:

答案 0 :(得分:1)

JSON是一个JavaScript对象。在javascript中,没有长片或花车或双打。一切都是数字,它在背景中都使用了双倍。所以当你发送JSON时,除非你告诉它将一个值明确地解释为long,否则它必须假设它可以是任何有效数字 - 它必须假设它是一个double。