java 中处理接口数据时,通常使用包装类(如 integer、double)或基本类型(如 int、double)进行转换。核心做法是调用包装类的静态方法 valueof() 或构造器,配合 parseint() 等解析方法,将字符串或对象转为具体数值。若需自动装箱或拆箱,编译器会隐式处理,但手动转换能更明确地控制异常和空值。

如何将 JSON 字符串中的数字字段转为 int 类型?
直接回答:使用 Integer.parseInt() 或 Integer.valueOf() 将 JSON 中的数字字符串转换为 int。例如,从 JSON 提取出 "123" 后,调用 Integer.parseInt("123") 即可得到整数 123。注意处理 NumberFormatException 以防格式错误。

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonToIntExample {
public static void main(String[] args) throws Exception {
String json = "{\"age\": \"25\", \"score\": \"98.5\"}";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(json);
// 将字符串 "25" 转为 int
int age = Integer.parseInt(node.get("age").asText());
System.out.println("Age: " + age); // 输出: Age: 25
// 尝试将 "98.5" 转为 int 会抛出异常
try {
int score = Integer.parseInt(node.get("score").asText());
} catch (NumberFormatException e) {
System.out.println("Cannot parse score as int: " + e.getMessage());
}
}
}
预期结果:
- age 成功转为 int 25。
- score 因包含小数点,Integer.parseInt 抛出 NumberFormatException。
立即学习“Java免费学习笔记(深入)”;
如何安全地将可能为空的字符串转为 Double?
直接回答:使用 Double.parseDouble() 并包裹在 try-catch 块中,或先检查字符串是否为 null/empty。若为空,可返回默认值如 0.0。避免直接使用 Double.valueOf() 而不处理异常,因为它也会抛出 NumberFormatException。

public class SafeDoubleParse {
public static double parseSafe(String value, double defaultValue) {
if (value == null || value.isEmpty()) {
return defaultValue;
}
try {
return Double.parseDouble(value);
} catch (NumberFormatException e) {
return defaultValue;
}
}
public static void main(String[] args) {
System.out.println(parseSafe("12.34", 0.0)); // 输出: 12.34
System.out.println(parseSafe(null, -1.0)); // 输出: -1.0
System.out.println(parseSafe("abc", 0.0)); // 输出: 0.0
}
}
预期结果:
- 有效数字字符串返回对应 double 值。
- 空值或无效字符串返回传入的默认值,不抛异常。
当接口返回的数值超出 int 范围时会发生什么?
直接回答:若接口返回的数值超过 int 的最大值(2^31-1),使用 Integer.parseInt() 会抛出 NumberFormatException。此时应改用 Long.parseLong() 或 BigInteger 来处理大数,确保数据完整性。


















