最佳实践
核心原则
1. 优先使用路径表达式
// 推荐
String name = data.getStr("user.profile.name");
// 不推荐
JSONMap user = data.getMap("user");
JSONMap profile = user.getMap("profile");
String name = profile.getStr("name");
2. 提供默认值
int age = data.getInt("age", 0);
// 代替:
Integer age = data.getInt("age");
if (age == null) age = 0;
3. 使用链式操作
JSONMap request = new JSONMap()
.set("header.token", token)
.set("body.data", data);
4. 区分 put 和 set
json.put("a.b", 1); // key 不解析:{"a.b": 1}
json.set("a.b", 1); // key 解析为路径:{"a": {"b": 1}}
5. 子对象缓存
多次读取同一子路径下的不同字段时,先获取子对象:
JSONMap profile = data.getMap("user.profile");
String name = profile.getStr("name");
String email = profile.getStr("email");
避免的性能陷阱
- 不要在循环中频繁
new JSONMap(),复用对象 - 不要频繁调用
map.toString(),序列化开销大 getMap()返回内部引用而非副本,修改会反映到原对象
上一节:AI辅助开发 | 返回文档导航 | 下一章:附录 →