First write a tool class JsonUtils.java, and then adjust the class conversion //Convert list to string String cacheString = JsonUtils.objectToJson(list);
JsonUtils.java tool class
public class JsonUtils { // define the jackson object private static final ObjectMapper MAPPER = new ObjectMapper(); /** * Convert the object to a json string. * <p>Title: pojoToJson</p> * <p>Description: </p> * @param data * @return */ public static String objectToJson(Object data) { try { String string = MAPPER.writeValueAsString(data); return string; } catch (JsonProcessingException e) { e.printStackTrace (); } return null; } /** * Convert json result set to object * * @param jsonData json data * @param clazz object type in the object * @return */ public static <T> T jsonToPojo(String jsonData, Class<T> beanType) { try { T t = MAPPER.readValue(jsonData, beanType); return t; } catch (Exception e) { e.printStackTrace (); } return null; } /** * Convert json data to pojo object list * <p>Title: jsonToList</p> * <p>Description: </p> * @param jsonData * @param beanType * @return */ public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) { JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType); try { List<T> list = MAPPER.readValue(jsonData, javaType); return list; } catch (Exception e) { e.printStackTrace (); } return null; } }