![970671ea1e961145818e6940d0310e04.png](https://i-blog.csdnimg.cn/blog_migrate/c0c6ab7ff579da5fb494e436cb6059d7.jpeg)
本文主要梳理3个常用JSON工具方法:
- JSON字符串转换成Object
- JSON字符串转换成List
- Object转换成JSON字符串
特别注意:需要引入jackson依赖!
以下,展示JacksonUtil工具类的封装思路,全部为静态static方法,方便调用:
import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.ObjectMapper;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.IOException;import java.util.List;import java.util.Objects;public class JacksonUtil { private static final Logger logger = LoggerFactory.getLogger(JacksonUtil.class); private static ObjectMapper objectMapper; static { objectMapper = new ObjectMapper(); } /** * @return T * @throws * @description JSON字符串转换成Object * @params [json, clazz] */ public static T toObject(String json, Class clazz) { try { if (Objects.isNull(json) || "".equals(json)) { return null; } return objectMapper.readValue(json, clazz); } catch (IOException e) { e.printStackTrace(); } return null; } /** * @return T * @throws * @description JSON字符串转换成List * @params [json, valueTypeRef] */ public static T toList(String json, TypeReference valueTypeRef) { try { if (Objects.isNull(json) || "".equals(json)) { return null; } return objectMapper.readValue(json, valueTypeRef); } catch (Exception e) { e.printStackTrace(); } return null; } /** * @return java.lang.String * @throws * @description Object转换成JSON字符串 * @params [object] */ public static String toJSon(Object object) { if (Objects.isNull(objectMapper)) { objectMapper = new ObjectMapper(); } try { return objectMapper.writeValueAsString(object); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) { // TODO 1 JSON字符串转换成Object String jsonCountry = "{"name":"中国