首页 > 解决方案 > 在 apache camel 中将 json 转换为其他格式

问题描述

我是apache骆驼的新手。我能够从骆驼发送一个获取休息 api 的请求。我使用过spring boot camel微服务。现在如何将输出格式转换为任何其他格式并显示它?

import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;

@Component
public class RestAPIClientRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        restConfiguration().host("https://jsonplaceholder.typicode.com").port(80);
        from("timer:foo?repeatCount=1").
        to("rest:get:/posts/1")
            .log("${body}");
    }
}

结果如下所示:

"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et 
cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet 
architecto"

标签: javaapache-camel

解决方案


rest 组件首先返回经典的 java 输入流,您必须将输入流转换为 dto,然后您可以转换此示例中的任何类型,它是 xml

   restConfiguration().host("https://jsonplaceholder.typicode.com").port(80);
from("timer:foo?repeatCount=1").
to("rest:get:/posts/1")
    .unmarshal(new JacksonDataFormat(YourDto.class))
    .unmarshal().jacksonxml().log("${body}")


public class YourDto{
public int userId;
public int id;
public String title;
public String body;}

推荐阅读