Json字符串和Java实体类之间的相互转换(利用jackson实现)

2023-01-18 18:17:41

import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
*
* JSON工具类
*
*


* JSON与Object相互转换
*


*/

public class JSONUtil {

/**
 * 将对象转换为json格式字符串
 * 
 * @param Object
 * @return json string
 */
public static String toJSON(Object obj) {
    ObjectMapper om = new ObjectMapper();
    try {
        String json = om.writeValueAsString(obj);
        return json;
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return null;
}

/**
 * 
 * 将json形式字符串转换为java实体类
 * 
 */
public static <T> T parse(String jsonStr, Class<T> clazz) {
    ObjectMapper om = new ObjectMapper();
    T readValue = null;
    try {
        readValue = om.readValue(jsonStr, clazz);
    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return readValue;
}

}

  • 作者:weixin_37232894
  • 原文链接:https://blog.csdn.net/weixin_37232894/article/details/59482789
    更新时间:2023-01-18 18:17:41