首先加入依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
详细工具类:
@Slf4j
public class JsonUtil {
private static ObjectMapper objectMapper = new ObjectMapper();
public static String toJson(Object object) {
try{
return objectMapper.writeValueAsString(object) ;
}catch(JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
public static Object fromJson(String string,Class classType){
try{
return objectMapper.readValue(string,classType) ;
}catch(IOException e) {
e.printStackTrace();
}
return null;
}
}