8

我刚刚编码将一个双精度值数组放入JsonObject. 但是,当我打印它时,我所有的 double 值都转换为 int 值。有人可以帮助我了解背后发生的事情吗?请让我知道将原始数组放入的最佳方法JsonObject

public class JsonPrimitiveArrays {        
    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        double[] d = new double[]{1.0,2.0,3.0};
        jsonObject.put("doubles",d);
        System.out.println(jsonObject);            
    }        
}

输出:

{“双打”:[1,2,3]}

4

3 回答 3

7

查看它最终toStringnet.sf.json.JSONObject调用以下方法将数字转换为String此处为源代码):

public static String numberToString(Number n) {
        if (n == null) {
            throw new JSONException("Null pointer");
        }
        //testValidity(n);

        // Shave off trailing zeros and decimal point, if possible.

        String s = n.toString();
        if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
            while (s.endsWith("0")) {
                s = s.substring(0, s.length() - 1);
            }
            if (s.endsWith(".")) {
                s = s.substring(0, s.length() - 1);
            }
        }
        return s;
    }

它显然会尽可能地消除尾随的零(s = s.substring(0, s.length() - 1)如果字符串以零结尾)。

System.out.println(numberToString(1.1) + " vs " + numberToString(1.0));

给,

1.1 vs 1
于 2014-02-23T08:40:25.320 回答
7

它实际上没有被转换为int。唯一发生的事情是 JS 对象没有显示.0不相关的内容。

在您的示例程序中,将一些值从 更改double[] d = new double[]{1.0,2.0,3.0}

double[] d = new double[]{1.0,2.1,3.1}并运行程序。

您将实际观察它而不是转换为 int。您将得到的输出是{"doubles":[1,2.1,3.1]}

于 2014-02-23T08:31:13.303 回答
6

所有数字都是 Javascript 中的浮点数。所以,1.0 和 1 在 JS 中是一样的。int、float 和 double 没有区别。

由于 JSON 最终将成为 JS 对象,因此添加额外的 '.0' 是没有用的,因为 '1' 也代表一个浮点数。我想这样做是为了在传递的字符串中保存几个字节。

所以,你会在 JS 中得到一个浮点数,如果你把它解析回 Java,你应该得到一个双精度数。试试看。

同时,如果您对它在屏幕上的显示方式感兴趣,您可以尝试一些字符串格式,使其看起来像“1.0”。

于 2014-02-23T08:28:20.387 回答