Jackson API 中的 asDouble() 和 doubleValue() 有什么区别?

What is the difference between asDouble() and doubleValue() in Jackson API?

我在使用这些方法时有点困惑。如果两种方法 return 具有相同的值,那么为什么 Jackson API 提供了两种不同的方法?

根据 jackson-databind 2.2.0 API

public double asDouble()

Method that will try to convert value of this node to a Java double. Numbers are coerced using default Java rules; booleans convert to 0.0 (false) and 1.0 (true), and Strings are parsed using default Java language integer parsing rules. If representation can not be converted to an int (including structured types like Objects and Arrays), default value of 0.0 will be returned; no exceptions are thrown.

public double doubleValue()

Returns 64-bit floating point (double) value for this node, if and only if this node is numeric (isNumber() returns true). For other types returns 0.0. For integer values, conversion is done using coercion; this may result in overflows with BigInteger values.

示例:

public static void main(String[] args) throws IOException {
    String jsonString = "{\"name\":\"Altaf Java\",\"salary\":\"12345.67\",\"amount\":98765.43}";
    System.out.println(jsonString);
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode rootNode = objectMapper.readTree(jsonString);
    JsonNode salaryNode = rootNode.get("salary");
    System.out.println("salaryNode.isNumber()=" + salaryNode.isNumber());
    System.out.println("salaryNode.asDouble()="+salaryNode.asDouble());
    System.out.println("salaryNode.doubleValue()="+salaryNode.doubleValue());
    JsonNode amountNode = rootNode.get("amount");
    System.out.println("amountNode.isNumber()=" + amountNode.isNumber());
    System.out.println("amountNode.asDouble()=" + amountNode.asDouble());
    System.out.println("amountNode.doubleValue()=" + amountNode.doubleValue());
}

输出:

{"name":"Altaf Java","salary":"12345.67","amount":98765.43}
salaryNode.isNumber()=false
salaryNode.asDouble()=12345.67
salaryNode.doubleValue()=0.0
amountNode.isNumber()=true
amountNode.asDouble()=98765.43
amountNode.doubleValue()=98765.43

这里可以看到,salaryNode值为String类型。表示它不是数字。因此 doubleValue() 方法 returns 默认值 0.0amountNode 值是数字。因此 doubleValue() 方法 returns 其原始值 98765.43