赞
踩
gson工具类:
- import com.google.gson.*;
- import lombok.extern.slf4j.Slf4j;
-
- import java.util.ArrayList;
- import java.util.List;
-
- @Slf4j
- public class GsonUtils {
-
- //log日志
- //private static final Logger LOGGER = LoggerFactory.getLogger(GsonUtils.class);
-
- //不用创建对象,直接使用Gson.就可以调用方法
- private static Gson gson = null;
-
- //判断gson对象是否存在了,不存在则创建对象
- static {
- if (gson == null) {
- //gson = new Gson();
- //当使用GsonBuilder方式时属性为空的时候输出来的json字符串是有键值key的,显示形式是"key":null,而直接new出来的就没有"key":null的
- gson= new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
- }
- }
-
- //无参的私有构造方法
- private GsonUtils() {
-
- }
-
- /**
- * 将对象转成json格式
- * @param object
- * @return String
- */
- public static String beanToString(Object object) {
- String gsonString = null;
- try {
- if (gson != null) {
- gsonString = gson.toJson(object);
- }
- } catch (Exception e) {
- log.error("对象转换json异常",e);
- }
- return gsonString;
- }
-
- /**
- * 将json转成特定的cls的对象
- * @param gsonString
- * @param cls
- * @return
- */
- public static <T> T stringToBean(String gsonString, Class<T> cls) {
- T t = null;
- try {
- if (gson != null) {
- //传入json对象和对象类型,将json转成对象
- t = gson.fromJson(gsonString, cls);
- }
- } catch (JsonSyntaxException e) {
- log.error("非法json字符串",e);
- }
- return t;
- }
-
- /**
- * json字符串转成list
- * 解决泛型问题
- * 备注:
- * List<T> list=gson.fromJson(gsonString, new TypeToken<List<T>>() {}.getType());
- * 该方法会报泛型类型擦除问题
- * @param gsonString
- * @param cls
- * @param <T>
- * @return
- */
- public static <T> List<T> stringToList(String gsonString, Class<T> cls) {
- List<T> list = new ArrayList<T>();
- try {
- if(gson!=null){
- JsonArray array = new JsonParser().parse(gsonString).getAsJsonArray();
- for(final JsonElement elem : array){
- list.add(gson.fromJson(elem, cls));
- }
- }
- } catch (JsonSyntaxException e) {
- log.error("非法json字符串",e);
- }
- return list;
- }
-
- }
测试方法:
- @Test
- public void testListToString(){
- List<String> list=new ArrayList<>(Arrays.asList("11","12","13"));
- System.out.println("list集合:"+list);
-
- //将[11,12,13]转换为字符串"11,12,13"
- String collection=list.stream().collect(Collectors.joining(","));
- System.out.println("collection str:"+collection);
- }
-
- @Test
- public void testBeanToString(){
- CustomMarket market=new CustomMarket();
- market.setMarketId(7);
- market.setInclude(Arrays.asList("11","12","13"));
- market.setExclude(Arrays.asList("21","22","23"));
- String gsonStr = GsonUtils.beanToString(market);
- System.out.println("gsonStr:"+gsonStr);
- //gsonStr:{"marketId":7,"include":["11","12","13"],"exclude":["21","22","23"]}
- }
-
- @Test
- public void testStringToBean(){
- String gsonStr="{\"include\":[{\"audienceId\":103731,\"userAudienceId\":190021,\"mediaAudienceIds\":[]}],"
- + "\"exclude\":[{\"audienceId\":104540,\"userAudienceId\":104550,\"mediaAudienceIds\":[]}]}";
- Audience audience = GsonUtils.stringToBean(gsonStr, Audience.class);
- List<AudienceUserSelected> include = audience.getInclude();
- List<AudienceUserSelected> exclude =audience.getExclude();
- System.out.println("include audienceId:"+include.get(0).getAudienceId());
- System.out.println("exclude audienceId:"+exclude.get(0).getAudienceId());
- //include audienceId:103731
- //exclude audienceId:104540
-
- }
-
- @Test
- public void testStringToList(){
- String gsonStr="[{\"iden\":1,\"times\":[0]},{\"iden\":2,\"times\":[0]},{\"iden\":3,\"times\":[0]},{\"iden\":4,"
- + "\"times\":[0]},{\"iden\":5,\"times\":[0]},{\"iden\":6,\"times\":[0]},{\"iden\":0,\"times\":[0]}]";
- //方法一:用gson解析json对象数组
- // List<TimeSlot> timeSlots = new Gson()
- // .fromJson(gsonStr, new TypeToken<List<TimeSlot>>() {
- // }.getType());
-
- //方法二:
- List<TimeSlot> timeSlots = GsonUtils.stringToList(gsonStr, TimeSlot.class);
- for (TimeSlot timeSlot : timeSlots) {
- Integer iden=timeSlot.getIden();
- List<Integer> times = timeSlot.getTimes();
- System.out.println("iden:"+iden);
- System.out.println("times:"+times.toString());
- }
- }
测试类:
CustomMarket :
- @Data
- public class CustomMarket implements Serializable {
-
- private static final long serialVersionUID = 5449480257660129769L;
-
- /**
- * 交易市场id
- */
- private Integer marketId;
-
- /**
- * 包含
- */
- private List<String> include;
-
- /**
- * 排除
- */
- private List<String> exclude;
-
- }
- @Data
- public class Audience implements Serializable {
-
- private static final long serialVersionUID = 2949364089756452317L;
-
- /**
- * 包含
- */
- private List<AudienceUserSelected> include;
-
- /**
- * 排除
- */
- private List<AudienceUserSelected> exclude;
- }
- @Data
- public class AudienceUserSelected implements Serializable {
-
- private static final long serialVersionUID = -3775367505215832758L;
-
- /**
- * 人群包ID
- */
- private Long audienceId;
-
- /**
- * 商户人群包ID
- */
- private Long userAudienceId;
-
- /**
- * 媒体侧人群ID集合
- */
- private List<Integer> mediaAudienceIds;
- }
- @Data
- public class TimeSlot implements Serializable {
-
- private static final long serialVersionUID = 4913373453802986540L;
-
- /**
- * 投放星期 0-6
- */
- private Integer iden;
-
- /**
- * 投放小时 0-23
- */
- private List<Integer> times;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。