public class JacksonUtil { private static Logger logger = LoggerFactory.getLogger(JacksonUtil.class); private final static ObjectMapper objectMapper = new ObjectMapper(); public static ObjectMapper getInstance() { return objectMapper; } /** * bean、array、List、Map --> json * java对象转为json字符串 * @param obj * @return json string * @throws Exception */ public static String writeValueAsString(Object obj) { try { return getInstance().writeValueAsString(obj); } catch (JsonGenerationException e) { logger.error(e.getMessage(), e); } catch (JsonMappingException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } return null; } 测试用例: // 创建一个Java对象 User user = new User("Alice", 25); // 将对象转换为JSON字符串 String json = JacksonUtil.writeValueAsString(user); // 验证JSON字符串是否符合预期 String expectedJson = "{\"name\":\"Alice\",\"age\":25}"; Assert.assertEquals(expectedJson, json); /** * string --> bean、Map、List(array) * json字符串转为java对象 * @param jsonStr * @param clazz * @return obj * @throws Exception */ public static <T> T readValue(String jsonStr, Class<T> clazz) { try { return getInstance().readValue(jsonStr, clazz); } catch (JsonParseException e) { logger.error(e.getMessage(), e); } catch (JsonMappingException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } return null; } 测试用例: // 定义一个JSON字符串 String json = "{\"name\":\"Alice\",\"age\":25}"; // 将JSON字符串转换为User对象 User user = JacksonUtil.readValue(json, User.class); /** * string --> List<Bean>... *json字符串转为List<Bean>对象 * @param jsonStr * @param parametrized * @param parameterClasses * @param <T> * @return */ public static <T> T readValue(String jsonStr, Class<?> parametrized, Class<?>... parameterClasses) { try { JavaType javaType = getInstance().getTypeFactory().constructParametricType(parametrized, parameterClasses); return getInstance().readValue(jsonStr, javaType); } catch (JsonParseException e) { logger.error(e.getMessage(), e); } catch (JsonMappingException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } return null; } }
测试用例:
// 定义一个 JSON 字符串
String json = "[{\"name\":\"Alice\",\"age\":25},{\"name\":\"Bob\",\"age\":30}]";
// 将 JSON 字符串转换为 List<User> 对象
List<User> userList = JacksonUtil.readValue(json, List.class, User.class);