简体   繁体   English

Apache Camel:使用 Camel 方法将 JSON 转换为 POJO

[英]Apache Camel: Convert JSON to a POJO using Camel methods

I have a REST server which sends JSON in response body.我有一个 REST 服务器,它在响应正文中发送 JSON。 I have recently started reading about Apache Camel.我最近开始阅读有关 Apache Camel 的文章。 I use following to send requests to my REST service.我使用以下内容向我的 REST 服务发送请求。

from("direct:start").setHeader("token", simple("234da"))
                            .to("http://localhost:8088/foo/bar/?foo1=bar1");

Now the response will be a JSON, is there any way I get this JSON directly into a POJO using some method ahead of to() (something like this)?现在响应将是一个 JSON,有什么方法可以在to()之前使用某种方法将这个 JSON 直接放入 POJO(类似这样)?

to("http://localhost:8088/foo/bar/?foo1=bar1").toPOJO();

I would prefer a non Spring solution.我更喜欢非 Spring 解决方案。

Thanks谢谢

Apache Camel provides a component to marshal and unmarshal POJO to and from JSON. Apache Camel 提供了一个组件来对 POJO 与 JSON 进行编组和解组。

In your case, it would be :在您的情况下,它将是:

 from("direct:start").setHeader("token", simple("234da"))
 .to("http://localhost:8088/foo/bar/?foo1=bar1")
 .unmarshal().json();

By the way, you may need to configure your json library to do it and I suggest you take look at the official configuration .顺便说一句,您可能需要配置您的 json 库才能做到这一点,我建议您查看官方配置

Little details from my side - although late我身边的小细节——虽然晚了

Create jsonFormatter and then unmarshal with class you need创建 jsonFormatter 然后用你需要的类解组
JsonDataFormat jsonDataFormat = new JsonDataFormat(JsonLibrary.Jackson);
this can be used in marshalling这可以用于编组

from("direct:consume-rest")
.log("calling bean method...")
.to("http://localhost:8080/greeting?name=baba")
//.process(svProcessor) // any extra process if you want
.unmarshal().json(JsonLibrary.Jackson, Greeting.class)
.bean(GreetingHelper.class, "print")
.log("converted to bean ...")
.end()
;

Helper class method辅助类方法
public void print (@Body Greeting greeting) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM