Json字符串與實體集轉換工具類 — QS8

開始更新SpringBoot2.x 快速入門系列

本次分享一個常用的工具類,實體集與字符串互相轉換的工具類,也就是Json字符串的序列化與反序列化(基於Jackson)

Demo 下載: https://github.com/wangyushuai/springboot-quick-start

歡迎大家 star, follow,fork, 更多內容將持續更新哦。

目錄如下

  1. 對象轉換爲Json字符串
  2. Json字符串反序列化爲實體集
package com.example.springboot.util.json;

import java.io.IOException;

import org.springframework.util.StringUtils;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 *  Json字符串轉換工具類
 * @author [email protected]
 * @date 2018/10/26
 */
public class JsonUtils {

    private static ObjectMapper objectMapper = new ObjectMapper();
    
    //對象轉字符串
    public static <T> String obj2String(T obj){
        if (obj == null){
            return null;
        }
        try {
            return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    //字符串轉對象
    public static <T> T string2Obj(String str,Class<T> clazz){
        if (StringUtils.isEmpty(str) || clazz == null){
            return null;
        }
        try {
            return clazz.equals(String.class)? (T) str :objectMapper.readValue(str,clazz);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章