1.2 五分钟上手
5 分钟内掌握 JSONMap 基本用法。
示例1:深层路径访问
import com.dlz-kit.json.JSONMap;
public class QuickStart {
public static void main(String[] args) {
String json = "{\"user\":{\"name\":\"张三\",\"profile\":{\"city\":\"北京\",\"age\":25}}}";
JSONMap data = new JSONMap(json);
String name = data.getStr("user.name"); // 张三
String city = data.getStr("user.profile.city"); // 北京
Integer age = data.getInt("user.profile.age"); // 25
}
}
对比传统方式:
// 传统方式:10+ 行,每层都要判空和强转
Map<String, Object> data = parseJson(json);
String city = null;
if (data != null && data.get("user") != null) {
Map user = (Map) data.get("user");
if (user.get("profile") != null) {
Map profile = (Map) user.get("profile");
city = (String) profile.get("city");
}
}
// JSONMap:1 行
String city = new JSONMap(json).getStr("user.profile.city");
示例2:智能构建嵌套结构
JSONMap config = new JSONMap()
.set("server.host", "localhost")
.set("server.port", 8080)
.set("db.master.url", "jdbc:mysql://localhost:3306/test")
.set("db.master.username", "root")
.add("whitelist", "192.168.1.1")
.add("whitelist", "192.168.1.2");
// 输出:
// {"server":{"host":"localhost","port":8080},"db":{"master":{"url":"jdbc:mysql://...","username":"root"}},"whitelist":["192.168.1.1","192.168.1.2"]}
set() 自动创建中间层级,无需手动 new HashMap。
示例3:类型自动转换
JSONMap data = new JSONMap();
data.put("score", "99.5"); // 存的是字符串
data.put("count", 100); // 存的是整数
Integer scoreInt = data.getInt("score"); // 99
Double scoreDouble = data.getDouble("score"); // 99.5
String countStr = data.getStr("count"); // "100"
Long countLong = data.getLong("count"); // 100L
示例4:数组操作
String json = "{\"users\":[" +
"{\"name\":\"张三\",\"age\":25}," +
"{\"name\":\"李四\",\"age\":30}," +
"{\"name\":\"王五\",\"age\":28}" +
"]}";
JSONMap data = new JSONMap(json);
String firstName = data.getStr("users[0].name"); // 张三
String lastName = data.getStr("users[-1].name"); // 王五(负索引)
JSONList users = data.getList("users");
核心操作速览
// 深层取值 — 路径不存在返回 null,不会 NPE
data.getStr("user.profile.city");
data.getStr("users[0].name");
data.getStr("users[-1].name"); // 负索引
// 智能构建 — 自动创建中间层
map.set("a.b.c", "value");
map.set("arr[0].name", "张三");
map.add("tags", "tag1"); // 自动创建数组并追加
// 类型转换
map.getStr(key); // 转字符串
map.getInt(key); // 转整数
map.getDouble(key); // 转小数
map.getBoolean(key); // 转布尔值
map.getList(key); // 转数组
map.getMap(key); // 转子对象
// 默认值
String name = data.getStr("user.name", "未知");
Integer age = data.getInt("user.age", 0);
// 链式操作
JSONMap request = new JSONMap()
.set("header.token", token)
.set("header.timestamp", System.currentTimeMillis())
.set("body.userId", userId);
// Bean 转换
JSONMap map = new JSONMap(user); // Bean → JSONMap
User user = map.as(User.class); // JSONMap → Bean
// 简化构造
JSONMap map = new JSONMap("name", "张三", "age", 25);
练习题
练习1:解析 API 响应
String apiResponse = "{\"code\":200,\"data\":{\"user\":{\"id\":123,\"name\":\"张三\"}}}";
// 提取 code、user.id、user.name
练习2:构建请求体
// 构建:
// {"header":{"version":"1.0","timestamp":...},"body":{"username":"zhangsan","password":"123456"}}
练习3:处理数组
String json = "{\"products\":[{\"name\":\"商品A\",\"price\":99.9},{\"name\":\"商品B\",\"price\":199.9}]}";
// 获取第一个商品名称、最后一个商品价格、计算总价
<details>
// 练习1
JSONMap response = new JSONMap(apiResponse);
Integer code = response.getInt("code");
Long userId = response.getLong("data.user.id");
String userName = response.getStr("data.user.name");
// 练习2
JSONMap request = new JSONMap()
.set("header.version", "1.0")
.set("header.timestamp", System.currentTimeMillis())
.set("body.username", "zhangsan")
.set("body.password", "123456");
// 练习3
JSONMap data = new JSONMap(json);
String firstName = data.getStr("products[0].name");
Double lastPrice = data.getDouble("products[-1].price");
JSONList products = data.getList("products");
double total = 0;
for (int i = 0; i < products.size(); i++) {
total += products.getDouble(i + ".price");
}
</details>