对象与字符串相互转换

朴灿烈づ我的快乐病毒、 2022-05-29 09:07 348阅读 0赞
  1. import com.google.common.collect.Lists;
  2. import com.mmall.pojo.Category;
  3. import com.mmall.pojo.TestPojo;
  4. import com.mmall.pojo.User;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.apache.commons.lang.StringUtils;
  7. import org.codehaus.jackson.map.DeserializationConfig;
  8. import org.codehaus.jackson.map.ObjectMapper;
  9. import org.codehaus.jackson.map.SerializationConfig;
  10. import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
  11. import org.codehaus.jackson.type.JavaType;
  12. import org.codehaus.jackson.type.TypeReference;
  13. import java.io.IOException;
  14. import java.text.SimpleDateFormat;
  15. import java.util.Date;
  16. import java.util.HashMap;
  17. import java.util.List;
  18. import java.util.Map;
  19. /**
  20. * Created by geely
  21. */
  22. @Slf4j
  23. public class JsonUtil {
  24. private static ObjectMapper objectMapper = new ObjectMapper();
  25. static{
  26. //1 对象的所有字段全部列入
  27. objectMapper.setSerializationInclusion(Inclusion.ALWAYS);
  28. //2 取消默认转换timestamps形式
  29. //timestamps 时间戳 1521353913377
  30. // true时为date转化为timestamps
  31. //false时为 2018-03-18T06:20:21.045+0000
  32. objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);
  33. //3 忽略空Bean转json的错误
  34. objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);
  35. //4 所有的日期格式都统一为以下的样式,即yyyy-MM-dd HH:mm:ss 4的优先级大于2
  36. objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.STANDARD_FORMAT));
  37. // 忽略 在json字符串中存在,但是在java对象中不存在对应属性的情况。防止错误
  38. objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
  39. }
  40. public static <T> String obj2String(T obj){
  41. if(obj == null){
  42. return null;
  43. }
  44. try {
  45. return obj instanceof String ? (String)obj : objectMapper.writeValueAsString(obj);
  46. } catch (Exception e) {
  47. log.warn("Parse Object to String error",e);
  48. return null;
  49. }
  50. }
  51. public static <T> String obj2StringPretty(T obj){
  52. if(obj == null){
  53. return null;
  54. }
  55. try {
  56. return obj instanceof String ? (String)obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
  57. } catch (Exception e) {
  58. log.warn("Parse Object to String error",e);
  59. return null;
  60. }
  61. }
  62. public static <T> T string2Obj(String str,Class<T> clazz){
  63. if(StringUtils.isEmpty(str) || clazz == null){
  64. return null;
  65. }
  66. try {
  67. return clazz.equals(String.class)? (T)str : objectMapper.readValue(str,clazz);
  68. } catch (Exception e) {
  69. log.warn("Parse String to Object error",e);
  70. return null;
  71. }
  72. }
  73. public static <T> T string2Obj(String str, TypeReference<T> typeReference){
  74. if(StringUtils.isEmpty(str) || typeReference == null){
  75. return null;
  76. }
  77. try {
  78. return (T)(typeReference.getType().equals(String.class)? str : objectMapper.readValue(str,typeReference));
  79. } catch (Exception e) {
  80. log.warn("Parse String to Object error",e);
  81. return null;
  82. }
  83. }
  84. public static <T> T string2Obj(String str,Class<?> collectionClass,Class<?>... elementClasses){
  85. JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);
  86. try {
  87. return objectMapper.readValue(str,javaType);
  88. } catch (Exception e) {
  89. log.warn("Parse String to Object error",e);
  90. return null;
  91. }
  92. }
  93. public static void main(String[] args) {
  94. // TestPojo testPojo = new TestPojo();
  95. // testPojo.setName("Geely");
  96. // testPojo.setId(666);
  97. //
  98. // //{"name":"Geely","id":666}
  99. String json = "{\"name\":\"Geely\",\"color\":\"blue\",\"id\":666}";
  100. TestPojo testPojoObject = JsonUtil.string2Obj(json,TestPojo.class);
  101. // String testPojoJson = JsonUtil.obj2String(testPojo);
  102. // log.info("testPojoJson:{}",testPojoJson);
  103. // log.info("end");
  104. //
  105. User user = new User();
  106. user.setId(2);
  107. user.setEmail("geely@happymmall.com");
  108. user.setCreateTime(new Date());
  109. String userJsonPretty = JsonUtil.obj2StringPretty(user);
  110. log.info("userJson:{}",userJsonPretty);
  111. // User u1 = new User();
  112. // u1.setId(1);
  113. // u1.setEmail("geelyu2@happymmall.com");
  114. //
  115. // User u2 = new User();
  116. // u2.setId(1);
  117. // u2.setEmail("geelyu2@happymmall.com");
  118. //
  119. //
  120. //
  121. // String user1Json = JsonUtil.obj2String(u1);
  122. //
  123. // String user1JsonPretty = JsonUtil.obj2StringPretty(u1);
  124. //
  125. // log.info("user1Json:{}",user1Json);
  126. //
  127. // log.info("user1JsonPretty:{}",user1JsonPretty);
  128. //
  129. //
  130. // User user = JsonUtil.string2Obj(user1Json,User.class);
  131. //
  132. // List<User> userList = Lists.newArrayList();
  133. // userList.add(u1);
  134. // userList.add(u2);
  135. //
  136. // String userListStr = JsonUtil.obj2StringPretty(userList);
  137. //
  138. // log.info("==================");
  139. //
  140. // log.info(userListStr);
  141. //
  142. // List<User> userListObj1 = JsonUtil.string2Obj(userListStr, new TypeReference<List<User>>() {
  143. // });
  144. //
  145. //
  146. // List<User> userListObj2 = JsonUtil.string2Obj(userListStr,List.class,User.class);
  147. //
  148. // System.out.println("end");
  149. }

发表评论

表情:
评论列表 (有 0 条评论,348人围观)

还没有评论,来说两句吧...

相关阅读