JsonUtils的实现:对象与json相互转换

pom.xml依赖


      com.fasterxml.jackson.core
      jackson-databind
      2.6.1
 

JsonUtils.java 内容:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by Bill.Tang on 2018-9-27.
 */

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

    /**
     * 将对象转换成json字符串。
     */
    public static String objectToJson(Object data) {
        try {
            String string = MAPPER.writeValueAsString(data);
            return string;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
 /**
     * 将json结果集转化为对象
     */
    public static  T jsonToPoJo(String jsonData, Class beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
             e.printStackTrace();
        }
        return null;
    }
    /**
     * 将json数据转换成pojo对象list
     */
    public  static  T jsonToList(String jsonData,TypeReference typeReference) {
        try {
            return MAPPER.readValue(jsonData, typeReference);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

使用例子代码

List deviceIdBeanResList = 
JsonUtils.parseJson("your json", new TypeReference>() {
        });

 

你可能感兴趣的:(java,json)