您现在的位置是:首页 > 个人博客日记 个人博客日记

JsonUtils工具类,json转为object和list,将对象转换成json字符串

2019-09-05 15:04:03

记录一个操作Object和Json互转的类

  1. package cn.w959.exhibit.base.utils;
  2. import com.fasterxml.jackson.core.JsonProcessingException;
  3. import com.fasterxml.jackson.databind.DeserializationFeature;
  4. import com.fasterxml.jackson.databind.JavaType;
  5. import com.fasterxml.jackson.databind.ObjectMapper;
  6. import java.io.Serializable;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. public class JsonUtils implements Serializable{
  10. /**
  11. * @author gaodeqiang
  12. * @version V1.0
  13. * @Description: json工具类
  14. */
  15. private static final long serialVersionUID = 1L;
  16. // 定义jackson对象
  17. private static final ObjectMapper MAPPER = new ObjectMapper();
  18. /**
  19. * 将对象转换成json字符串。
  20. */
  21. public static String objectToJson(Object data) {
  22. try {
  23. String string = MAPPER.writeValueAsString(data);
  24. return string;
  25. } catch (JsonProcessingException e) {
  26. e.printStackTrace();
  27. }
  28. return "";
  29. }
  30. /**
  31. * 将json结果集转化为对象
  32. *
  33. * @param jsonData json数据
  34. * @param
  35. */
  36. public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
  37. MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  38. try {
  39. T t = MAPPER.readValue(jsonData, beanType);
  40. return t;
  41. } catch (Exception e) {
  42. e.printStackTrace();
  43. }
  44. return null;
  45. }
  46. /**
  47. * 将json数据转换成pojo对象list
  48. * <p>Title: jsonToList</p>
  49. * <p>Description: </p>
  50. * @param jsonData
  51. * @param beanType
  52. */
  53. public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
  54. JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
  55. try {
  56. List<T> list = MAPPER.readValue(jsonData, javaType);
  57. return list;
  58. } catch (Exception e) {
  59. e.printStackTrace();
  60. }
  61. return new ArrayList<T>();
  62. }
  63. }


关注TinyMeng博客,更多精彩分享,敬请期待!
 

站点信息