Hutool 的完整 JSON 工具类示例
Hutool 的完整 JSON 工具类示例,覆盖:
Bean → JSON
List → JSON
JSON → Bean
JSON → List(支持泛型)
JSON → Map / List<Map>
Hutool 的 API 非常简洁,一行即可搞定,适合“快速开发”场景。
1️⃣ Maven 依赖
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.25</version>
</dependency>
2️⃣ 示例实体类(同上)
@Data
public class User {private Long id;private String name;private LocalDateTime createTime;
}
3️⃣ 工具类封装(可选,一行即可)
Hutool 已提供静态方法,无需额外封装;下面给出一个简单包装,方便统一异常处理:
import cn.hutool.json.JSONUtil;
import cn.hutool.json.TypeReference;import java.util.List;
import java.util.Map;public class HutoolJsonUtil {/** 对象 → JSON */public static String toJson(Object obj) {return JSONUtil.toJsonStr(obj);}/** JSON → Bean */public static <T> T toBean(String json, Class<T> clazz) {return JSONUtil.toBean(json, clazz);}/** JSON → List<Bean> */public static <T> List<T> toList(String json, Class<T> clazz) {return JSONUtil.toList(JSONUtil.parseArray(json), clazz);}/** JSON → Map */public static Map<String, Object> toMap(String json) {return JSONUtil.toBean(json, new TypeReference<Map<String, Object>>() {});}/** JSON → List<Map> */public static List<Map<String, Object>> toListMap(String json) {return JSONUtil.toBean(json, new TypeReference<List<Map<String, Object>>>() {});}
}
4️⃣ 使用示例
public class HutoolJsonDemo {public static void main(String[] args) {// 构造数据User user1 = new User(1L, "张三", LocalDateTime.now());User user2 = new User(2L, "李四", LocalDateTime.now());List<User> userList = List.of(user1, user2);// 1. Bean → JSONString userJson = HutoolJsonUtil.toJson(user1);System.out.println("Bean → JSON: " + userJson);// 2. List → JSONString listJson = HutoolJsonUtil.toJson(userList);System.out.println("List → JSON: " + listJson);// 3. JSON → BeanUser userObj = HutoolJsonUtil.toBean(userJson, User.class);System.out.println("JSON → Bean: " + userObj);// 4. JSON → List<Bean>List<User> users = HutoolJsonUtil.toList(listJson, User.class);System.out.println("JSON → List<Bean>: " + users);// 5. JSON → Map / List<Map>Map<String, Object> map = HutoolJsonUtil.toMap(userJson);System.out.println("JSON → Map: " + map);}
}
5️⃣ 控制台输出示例复制
Bean → JSON: {"id":1,"name":"张三","createTime":"2024-06-01 15:30:00"}
List → JSON: [{"id":1,"name":"张三","createTime":"2024-06-01 15:30:00"},{"id":2,"name":"李四","createTime":"2024-06-01 15:30:00"}]
JSON → Bean: User(id=1, name=张三, createTime=2024-06-01T15:30)
JSON → List<Bean>: [User(...), User(...)]
JSON → Map: {id=1, name=张三, createTime=2024-06-01 15:30:00}
✅ 总结
场景 | Hutool 方法 |
---|---|
Bean → JSON | JSONUtil.toJsonStr(obj) |
List → JSON | JSONUtil.toJsonStr(list) |
JSON → Bean | JSONUtil.toBean(json, Bean.class) |
JSON → List | JSONUtil.toList(JSONUtil.parseArray(json), Bean.class) |
JSON → Map | JSONUtil.toBean(json, new TypeReference<>(){}) |