JojoMiss

疯魔jojo的后花园

导航

groovy 字符串、json 动态拼接内容、 组数动态追加键值对

1.字符串拼接

def ids = [21321,3445,3456];
def size=ids.size();
vars.put("skuNum",size);
logs.add('sku数量:'+size);
StringBuffer sb = new StringBuffer();
def random = new java.util.Random();
for (int i = 0; i < size; i++) {
    def skuId = ids[i]
    binding.setVariable("skuId"+i, skuId);
    def count = random.nextInt(6)+2;//下单时每个skuID随机赋值一个下单数量
    def subOrderId = random.nextInt(999999)+1;
    vars.put("cnt",count);
    binding.setVariable("count"+i, count);
    logs.add('skuID:'+binding.getVariable("skuId"+i)+"   数量:"+binding.getVariable("count"+i));
    sb.append("{\"skuId\":"+binding.getVariable("skuId"+i)+",\"productName\":\"goapi测试\",\"saleCount\":"+binding.getVariable("count"+i)+",\"originPrice\":0.02,\"subtotalAmount\":0.04,\"couponTotalAmount\":0.01,\"activityTotalAmount\":0.01,\"outSkuld\":\""+binding.getVariable("skuId"+i)+"\",\"subOrderld\":\""+subOrderId+"\"},");
}
def orderSkus=sb.toString().substring(0, sb.toString().length() - 1);
vars.put("orderSkus",orderSkus);
logs.add('拼接后的字符串:'+orderSkus);
if(${channelId} == 6801669){
  def dateNow=${dateNow}+"A";
  vars.put("dateNow",dateNow);
  logs.add('抖音订单号:'+dateNow);
}

2.json 拼接

import groovy.json.JsonSlurper
def ReturnAddressDTO = runVars.get('ReturnAddressDTO');//获取上游的json对象,此时拿到的是String
def jsonObject = new JsonSlurper().parseText(ReturnAddressDTO)//转换为 jsonObject
jsonObject.put("policyTimeInDay",30);
jsonObject.put("policyType",1);
vars.put("ReturnAddressDTO",jsonObject);

3、数组动态增加键值对

上游输出json:
expensesInfo: [{"itemId":470207765,"skuId":472362734,"expensesInnerVO":[{"pointDeduction":15.0,"pointAssign":["网易再顾:5.00% ","严选贸易:10.00% "],"startTime":1689868800000,"endTime":1704038399999}]}]
------------------------------------------------------------------------
import groovy.json.JsonSlurper
import java.text.DateFormat
import java.text.SimpleDateFormat

def timestampToDateInt(timestamp) {
    // 毫秒时间戳转换日期格式:2023-04-21
    def date = new Date(timestamp)
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd")
    def formattedDate = dateFormat.format(date)
    return formattedDate
}
def expensesInfo = new JsonSlurper().parseText(runVars.get('expensesInfo'))
def startDate = expensesInfo[0].expensesInnerVO[0].startTime
def endDate = expensesInfo[0].expensesInnerVO[0].endTime
logs.add('开始日期:' + startDate + '\n结束日期:' + endDate)

startDate = timestampToDateInt(startDate)
endDate = timestampToDateInt(endDate)
logs.add('开始日期:' + startDate + '\n结束日期:' + endDate)

// 将新的键值对存储到Map中
def newKeyValuePairs = [
    postageEffectiveDate1: startDate.toString(),
    postageExpirationDate1: endDate.toString()
]
// 将Map放回原始的JSON对象中
expensesInfo[0].expensesInnerVO[0].putAll(newKeyValuePairs)
vars.put("expensesInfo", new groovy.json.JsonBuilder(expensesInfo).toPrettyString())
logs.add('日志信息:\n' + expensesInfo)

 

posted on 2024-04-01 13:09  幽忧一世  阅读(226)  评论(1编辑  收藏  举报

⭐️CSDN 我的文章列表⭐️
⭐WEIBO 微博首页⭐️
⭐园子 我的院子⭐️