跳到主要内容

JSONMap 完整指南

返回文档导航 | JSONList 完整指南


JSONMap 继承 HashMap<String, Object>,为 JSON 嵌套数据提供路径取值、自动类型转换、链式构建能力。


构造方式

// 空对象
JSONMap map = new JSONMap();

// JSON 字符串
JSONMap map = new JSONMap("{\"name\":\"张三\",\"age\":25}");

// 从 Map
Map<String, Object> hashMap = new HashMap<>();
JSONMap map = new JSONMap(hashMap);

// 从 Java Bean(字段值拷贝)
User user = new User();
JSONMap map = new JSONMap(user);

// 键值对构造
JSONMap map = new JSONMap("name", "张三", "age", 25, "city", "北京");

// 静态工厂方法
JSONMap map = JSONMap.createJsonMap(data);

JSON 字符串支持标准格式、简化格式(key 可不加引号)、带注释的 JSON:

// 简化格式(单引号)
JSONMap map = new JSONMap("{name:'张三',age:25}");

// 带注释
JSONMap map = new JSONMap("{\n" +
" name: '张三', // 用户姓名\n" +
" age: 25\n" +
"}");

深层路径访问

核心方法:getStr / getInt / getLong / getDouble / getBigDecimal / getBoolean / getMap / getList / getObj

所有 get 方法:路径不存在返回 null 或默认值,不会 NPE。

JSONMap data = new JSONMap("{\"user\":{\"name\":\"张三\",\"age\":25,\"tags\":[\"vip\",\"active\"]}}");

// 点号穿透嵌套对象
String name = data.getStr("user.name"); // 张三
Integer age = data.getInt("user.age"); // 25
JSONMap profile = data.getMap("user"); // {"name":"张三","age":25}

// 数组索引
String firstTag = data.getStr("user.tags[0]"); // vip
String lastTag = data.getStr("user.tags[-1]"); // active(负索引)

// 混合路径
// data.getStr("orders[0].items[-1].product.name");

// 带默认值
String city = data.getStr("user.city", "未知");

路径语法

语法说明示例
.对象属性user.name
[n]数组索引users[0]
[-n]负索引(倒数)users[-1]
混合任意组合users[0].profile.tags[-1]

类型转换

get 方法自动将值转换到目标类型,无论源数据是什么类型:

JSONMap data = new JSONMap();
data.put("score", "99.5"); // 存的是字符串
data.put("count", 100); // 存的是整数
data.put("rate", 0.85); // 存的是小数

data.getInt("score"); // 99
data.getDouble("score"); // 99.5
data.getBigDecimal("score"); // 99.5
data.getStr("count"); // "100"
data.getLong("count"); // 100L
data.getFloat("rate"); // 0.85f

完整读取方法

// 基本类型
String getStr(String key)
String getStr(String key, String defaultValue)
Integer getInt(String key)
Integer getInt(String key, Integer defaultValue)
Long getLong(String key)
Double getDouble(String key)
Float getFloat(String key)
BigDecimal getBigDecimal(String key)
Boolean getBoolean(String key)
Date getDate(String key)

// 复杂类型
JSONMap getMap(String key)
JSONList getList(String key)
<T> List<T> getList(String key, Class<T> clazz)
<T> T[] getArray(String key, Class<T> clazz)
<T> T getObj(String key, Class<T> clazz)

// 对象转换
<T> T as(Class<T> clazz)
<T> Map<String, T> asMap(Class<T> clazz)

set / put / add — 写入

// set:解析路径,自动创建中间层
json.set("a.b.c", 1);
// → {"a":{"b":{"c":1}}}

// put:不解析路径,直接作键名
json.put("a.b", 1);
// → {"a.b":1}

// add:追加到数组,自动创建数组
json.add("tags", "tag1");
json.add("tags", "tag2");
// → {"tags":["tag1","tag2"]}

set 支持的路径格式:

json.set("user.profile.name", "张三"); // 嵌套对象
json.set("users[0].name", "张三"); // 数组索引
json.set("users[5].name", "王五"); // 自动补齐中间元素(null)
json.set("matrix[0][0]", 1); // 多维数组
json.set("config.servers[0].ports[0]", 8080); // 混合路径

removes — 深层删除

JSONMap json = new JSONMap()
.set("user.name", "张三")
.set("user.age", 25)
.set("items[0]", "项目1")
.set("items[1]", "项目2");

json.removes("user.age"); // 删除简单键
json.removes("items[1]"); // 删除数组元素,数组自动收缩
json.removes("nonexistent"); // 不存在不抛异常

写入方法

JSONMap put(String key, Object value) // 普通写入(key 不解析)
JSONMap set(String key, Object value) // 深层写入(key 解析为路径)
JSONMap removes(String key) // 深层删除
JSONMap add(String key, Object obj) // 数组追加
JSONMap clearEmptyProp() // 清除 null 和空字符串
String toString() // 转 JSON 字符串

实战场景

API 响应解析

String response = httpClient.get("/api/user/info");
JSONMap data = new JSONMap(response);

String avatar = data.getStr("data.user.profile.avatar", "default.png");
List<String> roles = data.getList("data.user.roles", String.class);
Integer age = data.getInt("data.user.age", 0);

动态构建请求体

JSONMap request = new JSONMap()
.set("header.version", "1.0")
.set("header.timestamp", System.currentTimeMillis())
.set("header.sign", generateSign())
.set("body.user.name", userName)
.set("body.user.email", email)
.add("body.user.tags", "vip");

表单数据处理

@PostMapping("/submit")
public Result submit(@RequestBody String formData) {
JSONMap form = new JSONMap(formData);
String name = form.getStr("name");
Integer age = form.getInt("age"); // "25" → 25
Boolean active = form.getBoolean("active");
User user = form.as(User.class);
return Result.success();
}

配置文件处理

JSONMap config = new JSONMap(readFile("config.json"));
int port = config.getInt("server.port", 8080);
String host = config.getStr("server.host", "localhost");
List<String> whitelist = config.getList("security.whitelist", String.class);

最佳实践

// 1. 优先用路径表达式,不用中间变量
String name = data.getStr("user.profile.name");

// 2. 提供默认值
int age = data.getInt("user.age", 0);

// 3. 链式构建
JSONMap request = new JSONMap()
.set("header.token", token)
.set("body.data", data);

// 4. 区分 put 和 set
json.put("a.b", 1); // {"a.b": 1} — key 不解析
json.set("a.b", 1); // {"a": {"b": 1}} — key 解析为路径

// 5. 子对象修改影响原对象(引用,不是副本)
JSONMap user = data.getMap("user");
user.put("age", 30);
data.getInt("user.age"); // 30

← 返回文档导航 | 下一节:JSONList完整指南 →