我使用 Camel Jolt 将输入 JSON 转换为其他格式输出 JSON,并且除了默认值之外,我的 Jolt JSON 转换不返回任何值(空或 null)。我的代码没有任何错误或警告,我将在此处附加我所有的代码快照。
pom.xml(依赖项)
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-spring-boot-starter</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-jolt-starter</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>4.0.1</version>
</dependency>
</dependencies>
CamelRoute.java
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
@Component
public class CamelRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
from("direct:transformInput")
.log("Received input JSON: ${body}")
.to("jolt:classpath:jolt-spec.json")
.log("Transformed output JSON: ${body}")
.to("log:finalOutput");
}
}
jolt-spec.json
[
{
"operation": "shift",
"spec": {
"inputField1": "outputField1",
"inputField2": "outputField2",
"nestedObject": {
"nestedField1": "outputNestedField1",
"nestedField2": "outputNestedField2"
}
}
}
]
TransformationController.java
import org.apache.camel.ProducerTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TransformationController {
@Autowired
private ProducerTemplate producerTemplate;
@PostMapping("/transform")
public String transform(@RequestBody String inputJson) {
// Send input JSON for transformation
String transformedOutput = producerTemplate.requestBody("direct:transformInput", inputJson, String.class);
// You can return the transformedOutput or perform further actions
return transformedOutput;
}
}
我在邮递员中使用以下输入 json 来点击 [POST]http://localhost:8080/transform
{
"inputField1": "value1",
"inputField2": "value2",
"nestedObject": {
"nestedField1": "nestedValue1",
"nestedField2": "nestedValue2"
}
}
程序运行良好,没有任何错误或警告。这是我的控制台日志:
23:44:23.393-04:00 INFO 29874 --- [nio-8080-exec-1] route1 : Received input JSON: {
"inputField1": "value1",
"inputField2": "value2",
"nestedObject": {
"nestedField1": "nestedValue1",
"nestedField2": "nestedValue2"
}
}
23:44:23.418-04:00 INFO 29874 --- [nio-8080-exec-1] route1 : Transformed output JSON:
23:44:23.418-04:00 INFO 29874 --- [nio-8080-exec-1] finalOutput : Exchange[ExchangePattern: InOut, BodyType: null, Body: [Body is null]]
转换后的输出 JSON 为空或 null,可能是什么原因?
这是一个奇怪的错误!在我添加 useHeadersAsParameters=true 作为查询参数后,它就可以工作了。
.to("jdbc:datasource?useHeadersAsParameters=true")