您可以使用映射模板来转换数据。
映射模板
是一个用
Velocity 模板语言(VTL)
表示的脚本,应用于使用
JSONPath
的负载。
以下示例显示了
PetStore 数据
转换的输入数据、映射模板和输出数据。
"id": 1,
"type": "dog",
"price": 249.99
"id": 2,
"type": "cat",
"price": 124.99
"id": 3,
"type": "fish",
"price": 0.99
#set($inputRoot = $input.path('$'))
#foreach($elem in $inputRoot)
"description" : "Item $elem.id is a $elem.type.",
"askingPrice" : $elem.price
}#if($foreach.hasNext),#end
"description" : "Item 1 is a dog.",
"askingPrice" : 249.99
"description" : "Item 2 is a cat.",
"askingPrice" : 124.99
"description" : "Item 3 is a fish.",
"askingPrice" : 0.99
|
下图显示了此映射模板的详细信息。
1 #set($inputRoot = $input.path('$'))
3 #foreach($elem in $inputRoot)
5 "description" : "Item $elem.id is a $elem.type.",
6 "askingPrice" : $elem.price
7 }#if($foreach.hasNext),#end
8 #end
在此映射模板中:
在第 1 行上,$inputRoot
变量表示上一部分的原始 JSON 数据中的根对象。指令以 #
符号开头。
在第 3 行上,foreach
循环遍历原始 JSON 数据中的每个对象。
在第 5 行上,description
是原始 JSON 数据中宠物的 id
和 type
拼接的结果。
在第 6 行上,askingPrice
是原始 JSON 数据中的 price
。
有关 Velocity 模板语言的更多信息,请参阅
Apache Velocity – VTL 参考
。有关 JSONPath 的更多信息,请参阅
JSONPath – 适用于 JSON 的 XPath
。
该映射模板假定基础数据为 JSON 对象。它不要求为数据定义模型。但是,输出数据的模型允许将前面的数据作为语言特定的对象返回。有关更多信息,请参阅
了解数据模型
。
复杂的映射模板
您还可以创建更复杂的映射模板。以下示例显示了引用连接和 100 的截止值,以确定宠物价格是否合适。
"id": 1,
"type": "dog",
"price": 249.99
"id": 2,
"type": "cat",
"price": 124.99
"id": 3,
"type": "fish",
"price": 0.99
#set($inputRoot = $input.path('$'))
#set($cheap = 100)
#foreach($elem in $inputRoot)
#set($name = "${elem.type}number$elem.id")
"name" : $name,
"description" : "Item $elem.id is a $elem.type.",
#if($elem.price > $cheap )#set ($afford = 'too much!') #{else}#set ($afford = $elem.price)#end
"askingPrice" : $afford
}#if($foreach.hasNext),#end
"name" : dognumber1,
"description" : "Item 1 is a dog.",
"askingPrice" : too much!
"name" : catnumber2,
"description" : "Item 2 is a cat.",
"askingPrice" : too much!
"name" : fishnumber3,
"description" : "Item 3 is a fish.",
"askingPrice" : 0.99