Gson gson = new Gson(); Sell sell = new sell(); Sell sell1 = gson.fromJson(SellJson,Sell.class);//json字符串转对象 String text = gson.toJson(sell);//对象转字符串 map、list转字符串 // listJson字符串转为list Type type = new TypeToken<ArrayList<String>>() { }.getType(); ArrayList<String> sList=gson.fromJson(listJsonStr, type);
在解析json数据时,若数据为一个数组,那可以使用TypeToKen来进行解析。
public static OrderDTO convert(OrderForm orderForm) { List<OrderDetail> orderDetailList = new ArrayList<>(); Gson gson = new Gson(); OrderDTO orderDTO = new OrderDTO(); try { orderDetailList = gson.fromJson(orderForm.getItems(), new TypeToken<List<OrderDetail>>(){}.getType()); }catch (Exception e){ log.error("【对象转换】 错误,string={}",orderForm.getItems()); throw new SellException(ExceptionEnum.PARAM_ERROE); } orderDTO.setOrderDetailList(orderDetailList); return orderDTO; }