M87星云

导航

java String转Json工具类


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
*
* @className json处理工具
*/
public class JsonUtill {

   //json字符串转对象
public static <T> T toObject(String json,Class<T> tClass){
try {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json,tClass);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}

   // 对象转json字符串
public static String toString(Object json){
try {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}

   // json数组转map对象
public static <K,V> Map<K,V> toMap(String json,Map<K,V> map){
try {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json,map.getClass());
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}

   // json字符串转list对象
public static <T> List<?> toList(String json,List<T> list){
try {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json,list.getClass());
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}

   // json 字符串转set对象
public static <T> Set<T> toSet(String json, Set<T> set){
try {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json,set.getClass());
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
}

posted on 2023-03-10 13:45  挽留匆匆的美丽  阅读(210)  评论(0编辑  收藏  举报