package com.xly.util; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.CollectionType; import com.fasterxml.jackson.databind.type.TypeFactory; import java.io.IOException; import java.util.List; public class JsonUtils { private static final ObjectMapper objectMapper = new ObjectMapper(); // JSON字符串转Java对象 public static T toObject(String json, Class clazz) { try { return objectMapper.readValue(json, clazz); } catch (IOException e) { throw new RuntimeException("JSON解析失败", e); } } // JSON字符串转List public static List toList(String json, Class clazz) { try { CollectionType listType = TypeFactory.defaultInstance() .constructCollectionType(List.class, clazz); return objectMapper.readValue(json, listType); } catch (IOException e) { throw new RuntimeException("JSON解析失败", e); } } // 对象转JSON字符串 public static String toJson(Object obj) { try { return objectMapper.writeValueAsString(obj); } catch (IOException e) { throw new RuntimeException("JSON生成失败", e); } } }