JSON型別資料轉換為物件,並排除指定的屬性.JAVA將購物車資料寫入到cookie中
阿新 • • 發佈:2019-01-05
public void addCart(HttpServletRequest request, HttpServletResponse response, Long skuId, Integer quantity) {
//獲取所有cookies
Cookie[] cookies = request.getCookies();
//獲取配置檔案中的購物車名稱
String cartName = ECPSUtils.readProp("cart_name");
//json資料轉換配置
JsonConfig jsonConfig = new JsonConfig();
//指定要轉換的類
jsonConfig.setRootClass(EbCart.class);
//指定要轉換的類中,排除轉換的屬性
jsonConfig.setExcludes(new String[]{"stu"});
//商品資訊
List<EbCart> carts = new ArrayList<EbCart>();
//查詢購物車是否已經存在商品
if(cookies != null && cookies.length > 0 ){
for (Cookie cookie : cookies) {
//如果使用者的請求已經包含了購物名稱,說明已經存在了購物車
if(StringUtils.equals(cartName, cookie.getName())){
//購物車資訊,並將購物 資訊進行編碼轉換
String cartInfo = cookie.getValue();
cartInfo = URLDecoder.decode(cartInfo);
//將購物車資訊轉換為json陣列
JSONArray jsonArray = JSONArray.fromObject(cartInfo);
//通過JSONSerializer 將json陣列轉換為java集合
JSONSerializer jsonSerializer = new JSONSerializer();
carts = (List<EbCart>) jsonSerializer.toJava(jsonArray, jsonConfig);
//設定標誌
boolean isExists = false;
//迴圈查詢要新增的商品是否已經存在,
if(carts.size() > 0){
for (EbCart cart : carts) {
//如果已經存在,則結束迴圈,並在已經存在的商品中加上本次購買的數量(注意:這裡對比時如果不使用longValue方法,就要使用equals來比較)
if(cart.getSkuId().longValue() == skuId.longValue()){
cart.setQuantity(cart.getQuantity()+quantity);
isExists = true;
break;
}
}
}
//如果要購買的商品在購物 車不存在,則將此商品加入到商品列表中
if(!isExists){
EbCart cart = new EbCart();
cart.setSkuId(skuId);
cart.setQuantity(quantity);
carts.add(cart);
}
}
}
}else{
//如果購物車不存在,則將要購物的商品放入到商品列表中
EbCart cart = new EbCart();
cart.setSkuId(skuId);
cart.setQuantity(quantity);
carts.add(cart);
}
//將JAVA集合轉換為json陣列
JSONArray jsonArray = JSONArray.fromObject(carts);
// jsonArray.add(carts);
//將java陣列轉換為字串,並重新編碼
String result = jsonArray.toString();
result = URLDecoder.decode(result);
//建立cookie,將購物車資訊放入進去。
Cookie cookie = new Cookie(cartName, result);
//設定cookie 的有效期
cookie.setMaxAge(Integer.MAX_VALUE);
//設定cookie的作用域
cookie.setPath("/");
//將cookie寫入到使用者的瀏覽器中
response.addCookie(cookie);
}