JSON parser in Java automatically converting a String to a number/integer

在 java如果直接把整數型別, 使用 Double.parseDouble(strNum) 會讓原本的整數 “100” 變成 “100.0” 的浮點數。

解法:
https://stackoverflow.com/questions/38356937/json-parser-in-java-automatically-converting-a-string-to-a-number-integer

/**
 * Try to convert a string into a number, boolean, or null. If the string
 * can't be converted, return the string.
 *
 * @param string
 *            A String.
 * @return A simple JSON value.
 */
public static Object stringToValue(String string) {
    if (string.equals("")) {
        return string;
    }
    if (string.equalsIgnoreCase("true")) {
        return Boolean.TRUE;
    }
    if (string.equalsIgnoreCase("false")) {
        return Boolean.FALSE;
    }
    if (string.equalsIgnoreCase("null")) {
        return JSONObject.NULL;
    }

    /*
     * If it might be a number, try converting it. If a number cannot be
     * produced, then the value will just be a string.
     */

    char initial = string.charAt(0);
    if ((initial >= '0' && initial <= '9') || initial == '-') {
        try {
            if (string.indexOf('.') > -1 || string.indexOf('e') > -1
                    || string.indexOf('E') > -1
                    || "-0".equals(string)) {
                Double d = Double.valueOf(string);
                if (!d.isInfinite() && !d.isNaN()) {
                    return d;
                }
            } else {
                Long myLong = new Long(string);
                if (string.equals(myLong.toString())) {
                    if (myLong.longValue() == myLong.intValue()) {
                        return Integer.valueOf(myLong.intValue());
                    }
                    return myLong;
                }
            }
        } catch (Exception ignore) {
        }
    }
    return string;
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *