gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:37:50 26 4
gpt4 key购买 nike

我在使用这些方法时有点困惑。如果两个方法返回相同的值,那么为什么 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() 方法返回默认值 0.0,但 amountNode 值是 Number。因此,doubleValue() 方法返回其原始值98765.43

关于java - Jackson API 中的 asDouble() 和 doubleValue() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60245267/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com