Я использую Apache Velocity для преобразования json, но столкнулся с некоторой проблемой.Ниже моя строка json
{
"apiCode": "Payment Execution Service",
"name": "Initiate a payment",
"description": "Initiate a payment",
"request": {
"method": "POST",
"path": "/api/v1/payments",
"headers": [
{
"Corporate-ID": "apiKey"
},
{
"Content-Type": "application/json"
}
],
"body": "{\n \"beneficiaryInformation\" : {\n \"destinationAccountIdentifier\" : \"string\",\n \"destinationBankIdentifier\" : \"DEUTDEDB237\",\n \"fullName\" : \"JASON SMITH\"\n },\n \"purposeOfPayment\" : \"Invoice Payment\",\n \"remittanceInformation\" : \"Mantainance of Fixtures\",\n \"remitterInformation\" : {\n \"sourceAccountCurrency\" : \"EUR\",\n \"sourceAccountIdentifier\" : \"string\",\n \"sourceBankIdentifier\" : \"DEUTDEDBFRA\"\n },\n \"transferAmount\" : 1.5,\n \"transferCurrency\" : \"EUR\",\n \"transferDate\" : \"2015-07-20\",\n \"transferType\" : \"SCTInst\",\n \"uniqueRequestNo\" : \"string\"\n}"
},
"response": {
"status": 200,
"headers": [
{
"Content-Type": "application/json"
}
],
"body": "{\n \"requestReferenceNo\" : \"string\",\n \"transactionStatus\" : {\n \"bankReferenceNo\" : \"string\",\n \"reasonCode\" : \"string\",\n \"statusCode\" : \"string\"\n }\n}"
},
"provider": "Payment Execution Service"
}
И ниже мой файл .vm
{
"provider": {
"name": "$arr[0].apiCode"
},
"consumer": {
"name": "$arr[0].provider"
},
"interactions": [
#set($i = 0)
#foreach($a in $arr)
{
"description": "$a.description",
"request": {
"path": "$a.request.path",
"method": "$a.request.method",
"headers": $json.valueToString($a.request.headers),
"body": $json.valueToString($a.request.body)
},
"response": {
"headers": $json.valueToString($a.response.headers),
"body": $json.valueToString($a.response.body),
"status": $a.response.status
},
"providerStates": [{
"name": "$a.description"
}]
}
#set($i = $i + 1)
#if ($i < $arr.size()), #end
#end
],
"metadata": {
"pact-jvm": {
"version": "3.6.3"
},
"pactSpecification": {
"version": "3.0.0"
}
}
}
Ниже вывод, который я получаю
{
"provider": {
"name": "Payment Execution Service"
},
"consumer": {
"name": "Payment Execution Service"
},
"interactions": [
{
"description": "Initiate a payment",
"request": {
"path": "/api/v1/payments",
"headers": [
{
"Corporate-ID": "apiKey"
},
{
"Content-Type": "application/json"
}
],
"method": "POST",
"body": "{\n \"beneficiaryInformation\" : {\n \"destinationAccountIdentifier\" : \"string\",\n \"destinationBankIdentifier\" : \"DEUTDEDB237\",\n \"fullName\" : \"JASON SMITH\"\n },\n \"purposeOfPayment\" : \"Invoice Payment\",\n \"remittanceInformation\" : \"Mantainance of Fixtures\",\n \"remitterInformation\" : {\n \"sourceAccountCurrency\" : \"EUR\",\n \"sourceAccountIdentifier\" : \"string\",\n \"sourceBankIdentifier\" : \"DEUTDEDBFRA\"\n },\n \"transferAmount\" : 1.5,\n \"transferCurrency\" : \"EUR\",\n \"transferDate\" : \"2015-07-20\",\n \"transferType\" : \"SCTInst\",\n \"uniqueRequestNo\" : \"string\"\n}"
},
"response": {
"headers": [
{
"Content-Type": "application/json"
}
],
"body": "{\n \"requestReferenceNo\" : \"string\",\n \"transactionStatus\" : {\n \"bankReferenceNo\" : \"string\",\n \"reasonCode\" : \"string\",\n \"statusCode\" : \"string\"\n }\n}",
"status": 200
},
"providerStates": [
{
"name": "Initiate a payment"
}
]
}
],
"metadata": {
"pact-jvm": {
"version": "3.6.3"
},
"pactSpecification": {
"version": "3.0.0"
}
}
}
, как и ожидалось
Ниже приведен мой java-код, который я пробовал
public String generatePACTUsingVelocity(List<ExchangeRequest> input) {
/* first, get and initialize an engine */
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
/* next, get the Template */
Template template = ve.getTemplate("spec/pact.vm");
StringWriter writer = new StringWriter();
VelocityContext context = new VelocityContext();
context.put("arr", objectToListHashMap(input));
context.put("json", JSONStringer.class);
template.merge(context, writer);
return writer.toString();
}
@SneakyThrows
private List<HashMap<String, Object>> objectToListHashMap(List<ExchangeRequest> input) {
List<HashMap<String, Object>> mapList = new ArrayList<HashMap<String, Object>>();
for (ExchangeRequest req : input) {
JSONObject obj = new JSONObject(req);
mapList.add(new ObjectMapper().readValue(obj.toString(), new TypeReference<HashMap<String, Object>>() {
}));
}
return mapList;
}
Есть ли другой способ написать шаблон .vm для достижения того же результата.Я не хочу использовать какой-либо класс Java в своем шаблоне, как я использовал JSONStringer.valueToString для преобразования JSON в строку Я хочу, чтобы мой шаблон был написан таким образом, чтобы любойтестер может написать и передать его в код для генерации вывода.