自动类型纠正
JSONMap 的 getXxx() 方法(如 getInt()、getStr())在取值时会自动对值进行类型转换,这是 ValUtil.toXxx() 提供的能力。
常见转换
JSONMap data = new JSONMap("{\"age\":\"25\",\"price\":\"99.9\",\"active\":\"true\",\"count\":\"3.0\"}");
Integer age = data.getInt("age"); // "25" → 25
Double price = data.getDouble("price"); // "99.9" → 99.9
Boolean active = data.getBoolean("active"); // "true" → true
Integer count = data.getInt("count"); // "3.0" → 3
String str = data.getStr("age"); // 25 → "25"
逗号分隔字符串转 List
data.put("ids", "1,2,3,4,5");
List<Integer> ids = data.getList("ids", Integer.class);
// → [1, 2, 3, 4, 5]
类型纠正机制
类型纠正由 ValUtil 实现,遵循有界宽容原则:
- 类型不同但能转换(如
"123"→123):自动转换 - 内容无法转换(如
"abc"→ 数字):抛出异常 - 值为 null 或空字符串:返回 null 或默认值
详见 ValUtil 类型转换 和 有界宽容原则。