import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionLikeType;
import java.util.List;
public class JsonUtils {
static ObjectMapper objectMapper = new ObjectMapper();
/**
* 字符串转对象
* @param str
* @param clazz
* @param <T>
* @return
*/
public static <T> T str2Obj(String str,Class<T> clazz){
T t=null;
try {
t=objectMapper.readValue(str,clazz);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return t;
}
/**
* 对象转字符串
* @param object
* @return
*/
public static String obj2Str(Object object){
try {
if (object!=null) {
return objectMapper.writeValueAsString(object);
}
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return "";
}
/**\
* 字符串转集合
* @param str
* @param clazz
* @param <T>
* @return
*/
public static <T> List<T> str2List(String str,Class<T> clazz){
CollectionLikeType collectionLikeType = objectMapper.getTypeFactory().constructCollectionType(List.class, clazz);
try {
List<T> list = objectMapper.readValue(str, collectionLikeType);
return list;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
jackson的字符串转换对象集合通用工具类
最新推荐文章于 2024-08-31 07:43:57 发布
本文介绍了如何使用Jackson库进行字符串到对象的转换,对象到字符串的转换,以及字符串到集合的转换。重点展示了`str2Obj`、`obj2Str`和`str2List`方法的使用,适合对Java JSON处理感兴趣的开发者。
411

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



