由于新接了一个商城系统,里面商品多规格设价的问题,需要把所有规格排列组合起来生成一个json供前端展示价格。
废话不多说贴上JAVA代码
public static JSONArray sku(List<Map<String,Object>> dataList,int size){
JSONArray jsonArray = new JSONArray();
sku2(jsonArray,dataList,new JSONObject(),size);
return jsonArray;
}
private static JSONObject sku2(JSONArray jsonArray,List<Map<String,Object>> dataList,JSONObject object,int size){
String skuName = "";//定义本次循环要循环的规格
for (Map<String,Object> data :dataList){
JSONObject newObject = JSONObject.parseObject(object.toJSONString());
if (newObject.get(data.get("skuName").toString())==null) {
if ("".equals(skuName)) {
newObject.put(data.get("skuName").toString(), data.get("skuValue"));
skuName = data.get("skuName").toString();//确定本次循环的规格 其余的跳过 如 宽度 1
}else {
if (!skuName.equals(data.get("skuName").toString())){
continue;
}
//覆盖本次规格 将宽度1 覆盖为宽度 2
newObject.put(data.get("skuName").toString(), data.get("skuValue"));
}
if (newObject.size()<size)// 未达到所要的规格数量 进入递归
sku2(jsonArray,dataList,newObject,size);
else{// 已达到 加入数组
newObject.put("price",0);
jsonArray.add(newObject);
}
}
}
return object;
}
public static void main(String[] args) {
List<Map<String,Object>> dataList = new ArrayList<>();
Map<String,Object> data = new HashMap<>();
data.put("skuName","长度");
data.put("skuValue",1);
dataList.add(data);
Map<String,Object> data1 = new HashMap<>();
data1.put("skuName","长度");
data1.put("skuValue",2);
dataList.add(data1);
Map<String,Object> data2 = new HashMap<>();
data2.put("skuName","高度");
data2.put("skuValue","3M");
dataList.add(data2);
JSONArray array = sku(dataList,2);
System.out.println(array.size());
System.out.println(array.toJSONString());
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)