JSON解析Utils

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

/**
 * @Auther zhoutf
 * @Date 2019/1/3 10:10
 * @Description
 */
public class JsonUtils {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json字符串。
     * 

Title: pojoToJson

*

Description:

* @param data * @return */ public static String objectToJson(Object data) { try { MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL); String string = MAPPER.writeValueAsString(data); return string; } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } /** * 将对象转换成json字符串。不含空值 *

Title: pojoToJson

*

Description:

* @param data * @return */ public static String objectToJsonNoNull(Object data) { try { MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL); String string = MAPPER.writeValueAsString(data); return string; } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } /** * 将json结果集转化为对象 * * @param jsonData json数据 * @param clazz 对象中的object类型 * @return */ public static T jsonToPojo(String jsonData, Class clazz) { try { T t = MAPPER.readValue(jsonData, clazz); return t; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 将json数据转换成pojo对象list *

Title: jsonToList

*

Description:

* @param jsonData * @param beanType * @return */ public static List jsonToList(String jsonData, Class beanType) { JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType); try { List list = MAPPER.readValue(jsonData, javaType); return list; } catch (Exception e) { e.printStackTrace(); } return null; } }

你可能感兴趣的:(Java开发的工具类utils)