当前位置:   article > 正文

gson工具类

gson工具类

gson工具类:

  1. import com.google.gson.*;
  2. import lombok.extern.slf4j.Slf4j;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. @Slf4j
  6. public class GsonUtils {
  7. //log日志
  8. //private static final Logger LOGGER = LoggerFactory.getLogger(GsonUtils.class);
  9. //不用创建对象,直接使用Gson.就可以调用方法
  10. private static Gson gson = null;
  11. //判断gson对象是否存在了,不存在则创建对象
  12. static {
  13. if (gson == null) {
  14. //gson = new Gson();
  15. //当使用GsonBuilder方式时属性为空的时候输出来的json字符串是有键值key的,显示形式是"key":null,而直接new出来的就没有"key":null的
  16. gson= new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
  17. }
  18. }
  19. //无参的私有构造方法
  20. private GsonUtils() {
  21. }
  22. /**
  23. * 将对象转成json格式
  24. * @param object
  25. * @return String
  26. */
  27. public static String beanToString(Object object) {
  28. String gsonString = null;
  29. try {
  30. if (gson != null) {
  31. gsonString = gson.toJson(object);
  32. }
  33. } catch (Exception e) {
  34. log.error("对象转换json异常",e);
  35. }
  36. return gsonString;
  37. }
  38. /**
  39. * 将json转成特定的cls的对象
  40. * @param gsonString
  41. * @param cls
  42. * @return
  43. */
  44. public static <T> T stringToBean(String gsonString, Class<T> cls) {
  45. T t = null;
  46. try {
  47. if (gson != null) {
  48. //传入json对象和对象类型,将json转成对象
  49. t = gson.fromJson(gsonString, cls);
  50. }
  51. } catch (JsonSyntaxException e) {
  52. log.error("非法json字符串",e);
  53. }
  54. return t;
  55. }
  56. /**
  57. * json字符串转成list
  58. * 解决泛型问题
  59. * 备注:
  60. * List<T> list=gson.fromJson(gsonString, new TypeToken<List<T>>() {}.getType());
  61. * 该方法会报泛型类型擦除问题
  62. * @param gsonString
  63. * @param cls
  64. * @param <T>
  65. * @return
  66. */
  67. public static <T> List<T> stringToList(String gsonString, Class<T> cls) {
  68. List<T> list = new ArrayList<T>();
  69. try {
  70. if(gson!=null){
  71. JsonArray array = new JsonParser().parse(gsonString).getAsJsonArray();
  72. for(final JsonElement elem : array){
  73. list.add(gson.fromJson(elem, cls));
  74. }
  75. }
  76. } catch (JsonSyntaxException e) {
  77. log.error("非法json字符串",e);
  78. }
  79. return list;
  80. }
  81. }

测试方法:

  1. @Test
  2. public void testListToString(){
  3. List<String> list=new ArrayList<>(Arrays.asList("11","12","13"));
  4. System.out.println("list集合:"+list);
  5. //将[11,12,13]转换为字符串"11,12,13"
  6. String collection=list.stream().collect(Collectors.joining(","));
  7. System.out.println("collection str:"+collection);
  8. }
  9. @Test
  10. public void testBeanToString(){
  11. CustomMarket market=new CustomMarket();
  12. market.setMarketId(7);
  13. market.setInclude(Arrays.asList("11","12","13"));
  14. market.setExclude(Arrays.asList("21","22","23"));
  15. String gsonStr = GsonUtils.beanToString(market);
  16. System.out.println("gsonStr:"+gsonStr);
  17. //gsonStr:{"marketId":7,"include":["11","12","13"],"exclude":["21","22","23"]}
  18. }
  19. @Test
  20. public void testStringToBean(){
  21. String gsonStr="{\"include\":[{\"audienceId\":103731,\"userAudienceId\":190021,\"mediaAudienceIds\":[]}],"
  22. + "\"exclude\":[{\"audienceId\":104540,\"userAudienceId\":104550,\"mediaAudienceIds\":[]}]}";
  23. Audience audience = GsonUtils.stringToBean(gsonStr, Audience.class);
  24. List<AudienceUserSelected> include = audience.getInclude();
  25. List<AudienceUserSelected> exclude =audience.getExclude();
  26. System.out.println("include audienceId:"+include.get(0).getAudienceId());
  27. System.out.println("exclude audienceId:"+exclude.get(0).getAudienceId());
  28. //include audienceId:103731
  29. //exclude audienceId:104540
  30. }
  31. @Test
  32. public void testStringToList(){
  33. String gsonStr="[{\"iden\":1,\"times\":[0]},{\"iden\":2,\"times\":[0]},{\"iden\":3,\"times\":[0]},{\"iden\":4,"
  34. + "\"times\":[0]},{\"iden\":5,\"times\":[0]},{\"iden\":6,\"times\":[0]},{\"iden\":0,\"times\":[0]}]";
  35. //方法一:用gson解析json对象数组
  36. // List<TimeSlot> timeSlots = new Gson()
  37. // .fromJson(gsonStr, new TypeToken<List<TimeSlot>>() {
  38. // }.getType());
  39. //方法二:
  40. List<TimeSlot> timeSlots = GsonUtils.stringToList(gsonStr, TimeSlot.class);
  41. for (TimeSlot timeSlot : timeSlots) {
  42. Integer iden=timeSlot.getIden();
  43. List<Integer> times = timeSlot.getTimes();
  44. System.out.println("iden:"+iden);
  45. System.out.println("times:"+times.toString());
  46. }
  47. }

测试类:

CustomMarket :

  1. @Data
  2. public class CustomMarket implements Serializable {
  3. private static final long serialVersionUID = 5449480257660129769L;
  4. /**
  5. * 交易市场id
  6. */
  7. private Integer marketId;
  8. /**
  9. * 包含
  10. */
  11. private List<String> include;
  12. /**
  13. * 排除
  14. */
  15. private List<String> exclude;
  16. }
  1. @Data
  2. public class Audience implements Serializable {
  3. private static final long serialVersionUID = 2949364089756452317L;
  4. /**
  5. * 包含
  6. */
  7. private List<AudienceUserSelected> include;
  8. /**
  9. * 排除
  10. */
  11. private List<AudienceUserSelected> exclude;
  12. }
  1. @Data
  2. public class AudienceUserSelected implements Serializable {
  3. private static final long serialVersionUID = -3775367505215832758L;
  4. /**
  5. * 人群包ID
  6. */
  7. private Long audienceId;
  8. /**
  9. * 商户人群包ID
  10. */
  11. private Long userAudienceId;
  12. /**
  13. * 媒体侧人群ID集合
  14. */
  15. private List<Integer> mediaAudienceIds;
  16. }
  1. @Data
  2. public class TimeSlot implements Serializable {
  3. private static final long serialVersionUID = 4913373453802986540L;
  4. /**
  5. * 投放星期 0-6
  6. */
  7. private Integer iden;
  8. /**
  9. * 投放小时 0-23
  10. */
  11. private List<Integer> times;
  12. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/834143
推荐阅读
  

闽ICP备14008679号