1. 程式人生 > >JsonUtils的實現:物件與json相互轉換

JsonUtils的實現:物件與json相互轉換

pom.xml依賴

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.6.1</version>
</dependency> 

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> T jsonToPoJo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
             e.printStackTrace();
        }
        return null;
    }
    /**
     * 將json資料轉換成pojo物件list
     */
    public  static <T> T jsonToList(String jsonData,TypeReference<T> typeReference) {
        try {
            return MAPPER.readValue(jsonData, typeReference);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

使用例子程式碼

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