简体   繁体   English

在 Apache Camel 中从 Json 检索对象

[英]Retrieve Object from Json in Apache Camel

I'm using Apache Camel and Spring Boot to build a servlet service.我正在使用Apache CamelSpring Boot来构建 servlet 服务。 I have a REST endpoint where I receive json objects.我有一个接收 json 对象的 REST 端点。 I want to read the json and map it into a POJO in my code.我想读取 json 并将其映射到我的代码中的 POJO。 Here's my RouteBuilder :这是我的RouteBuilder

public class MyRouteBuilder extends RouteBuilder{

    @Override
    public void configure() throws Exception {

    restConfiguration()
     .component("servlet")
     .host("localhost")
     .port("8080")
     .bindingMode(RestBindingMode.auto);

    rest("/say").post("/json").type(User.class).to("direct:json");
    from("direct:json").someUsefulMethod();
    }
}

Here's my User class :这是我的用户类

public class User {
    private String id;
    private String name;
    private String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

I followed the Apache documentation .我遵循了 Apache 文档 What I want to do is to inject a json like {"id":"123", "name":"elly", "age":"29"} into an instance of my User class.我想要做的是将像 {"id":"123", "name":"elly", "age":"29"} 这样的 json 注入到我的 User 类的实例中。 How do I take the data from the REST request?如何从 REST 请求中获取数据?
Thank all of you.谢谢大家。

EDIT AFTER ANSWER: for completeness this is the final example code in MyRouteBuilder class:回答后编辑:为了完整MyRouteBuilder这是MyRouteBuilder类中的最后一个示例代码:

    from("direct:json").process(new Processor() {
       public void process(Exchange exchange) throws Exception {
          User body = exchange.getIn().getBody(User.class);
          System.out.println("Input object: " + body.getName() + ", " + body.getAge());
          body.setAge("35");
          exchange.getIn().setBody(body);
          System.out.println("Output object: " + body.getName() + ", " + body.getAge());
       }
});

Add camel-jackson to the classpath so it can bind json to pojo.将 camel-jackson 添加到类路径,以便它可以将 json 绑定到 pojo。

See some of the rest examples at: https://github.com/apache/camel-examples/tree/master/examples查看其他一些示例: https : //github.com/apache/camel-examples/tree/master/examples

You can use jackson annotations on your POJOs to fine tune the binding您可以在 POJO 上使用 jackson 注释来微调绑定

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

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