spring-boot返回json数据(json字符串与对象互相转换封装)
封装类:
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;
import java.io.IOException;
/**
* QQ:728297725
* Created by liupeng on 2019/4/14.
*/
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;
}
}
}
调用实例:
//返回json实例 @RequestMapping(value="/httpJson", method = {RequestMethod.GET}) public String getJson(){ JObject object = new JObject("chengxi","970624"); Map<String,JObject> mapObject = new HashMap<String,JObject>(); mapObject.put("liupeng",object); return JsonUtils.obj2String(mapObject); }
更多推荐
所有评论(0)