import com.jayway.jsonpath.JsonPath
def path = vars.get("BaseFilePath") + "/" + vars.get("FhirVersion") + "/Get/Patient/";
def newLine = System.getProperty('line.separator')
def response = prev.getResponseDataAsString()
//address
def addressCSV = new File(path + 'address.csv')
def addressList = []
def addressCityCSV = new File(path + 'address-city.csv')
def cityList = []
def addressCountryCSV = new File(path + 'address-country.csv')
def countryList = []
def addressPostalCodeCSV = new File(path + 'address-postalcode.csv')
def postalCodeList = []
def addressStateCSV = new File(path + 'address-state.csv')
def stateList = []
def addressArray = JsonPath.read(response, '$..address')
addressArray.each { eachAddress ->
eachAddress.each { subAddress ->
subAddress.get('line').each { line ->
addressList.add(line)
}
cityList.add(subAddress.get('city'))
stateList.add(subAddress.get('state'))
postalCodeList.add(subAddress.get('postalCode'))
countryList(subAddress.get('country'))
}
addressList.unique().each { address ->
addressCSV << address << newLine
}
cityList.unique().each { city ->
addressCityCSV << city << newLine
}
countryList.unique().each { country ->
addressCountryCSV << country << newLine
}
postalCodeList.unique().each { postalCode ->
addressPostalCodeCSV << postalCode << newLine
}
stateList.unique().each { state ->
addressStateCSV << state << newLine
}
}
我在jmeter的JSR223后处理器中编写了此脚本,以从json响应中提取数据,addressList,cityList和其他列表包含重复元素,因此我想删除重复项并将唯一值推送到文件中。 但是此代码不起作用。有人可以帮我解决这个问题
答案 0 :(得分:0)
要仅保留唯一值,请使用Set
我们可以使用toSet()函数将List转换为Set。
因此您可以将其添加到相关列表中,如下所示:
uniqueStateCSVSet = addressStateCSV.toSet()
或预定义为
Set addressArray
答案 1 :(得分:0)
调用Collection.unique()函数应该可以解决问题,即
addressList = addressList.unique()
演示:
但是,如果您的集合包含自定义对象(即不正常的Strings),则需要提出一个特殊的Comparator实现,即
def myComparator = [
equals: { delegate.equals(it) },
compare: { source, target ->
source.someField <=> target.someField
}
] as Comparator
def unique = addressList.unique(myComparator)
有关更多Groovy技巧和窍门,请参见The Groovy Templates Cheat Sheet for JMeter