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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10191429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:00:24  来源:igfitidea点击:

Apache Camel: Covert JSON to a POJO using camel methods

javajsonapache-camel

提问by Sikorski

I have a REST server which sends JSON in response body. I have recently started reading about Apache Camel. I use following to send requests to my REST service.

我有一个 REST 服务器,它在响应正文中发送 JSON。我最近开始阅读有关 Apache Camel 的文章。我使用以下内容向我的 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,有什么方法可以使用某种方法将这个 JSON 直接放入 POJO 中to()(类似这样)?

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

I would prefer a non Spring solution.

我更喜欢非 Spring 解决方案。

Thanks

谢谢

回答by victor gallet

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 库才能做到这一点,我建议您查看官方配置

回答by shaILU

Little details from my side - although late

我身边的小细节——虽然晚了

Create jsonFormatter and then unmarshal with class you need
JsonDataFormat jsonDataFormat = new JsonDataFormat(JsonLibrary.Hymanson);
this can be used in marshalling

创建 jsonFormatter 然后用你需要的类解组
JsonDataFormat jsonDataFormat = new JsonDataFormat(JsonLibrary.Hymanson);
这可以在编组中使用

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.Hymanson, Greeting.class)
.bean(GreetingHelper.class, "print")
.log("converted to bean ...")
.end()
;

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.Hymanson, Greeting.class)
.bean(GreetingHelper.class, "print")
.log("converted to bean ...")
.end()
;

Helper class method
public void print (@Body Greeting greeting) {

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