package com.mqtt.util;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mqtt.entity.DevInfo;
import java.text.SimpleDateFormat;
import java.util.Date;
public class JsonUtils {
/**
* Obj转json
* @param o
* @param dateFormat
* @return
*/
public static String getJson(Object o,String dateFormat){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(simpleDateFormat);
String json = null ;
try {
json=mapper.writeValueAsString(o);
} catch (JsonProcessingException e) {
System.out.println("=====obj解析JSON异常=====");
}
return json;
}
/**
* obj转json
* @param o
* @return
*/
public static String getJson(Object o){
return getJson(o,DateUtils.dateFormat);
}
/**
* json转obj
* @param json
* @param dateFormat
* @param valueType
* @return
* @param <T>
*/
public static <T> T jsonToObj(String json,String dateFormat,Class<T> valueType){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(simpleDateFormat);
T t = null;
try {
t = mapper.readValue(json, valueType);
} catch (JsonProcessingException e) {
System.out.println("=====Json解析 obj 异常");
}
return t;
}
/**
* json转obj
* @param json
* @param valueType
* @return
* @param <T>
*/
public static <T> T jsonToObj(String json,Class<T> valueType){
return jsonToObj(json,DateUtils.dateFormat,valueType);
}
}
JSON工具类 基于jackson
于 2023-11-07 08:20:22 首次发布
该文章介绍了Java类JsonUtils中处理对象与JSON字符串之间的转换方法,包括使用ObjectMapper和自定义日期格式的实现。
2874

被折叠的 条评论
为什么被折叠?



