0

我正在尝试从 xml 文件中获取字符串并将其值设置为一个对象,但无法弄清楚如何执行此操作。这是我到目前为止所做的:

public class Converter {

public static void main(String[] args) throws Exception {

    final XmlJsonDataFormat xmlJsonFormat = new XmlJsonDataFormat();
    xmlJsonFormat.setTypeHints(String.valueOf("YES"));

    CamelContext context = new DefaultCamelContext();
    context.getTypeConverterRegistry().addTypeConverter(User.class, String.class, new UserConverter());        

    context.addRoutes(new RouteBuilder() {
        public void configure() {
            from("ftp://Mike@localhost")
                    .to("seda:input").marshal(xmlJsonFormat).to("seda:out");
        }
    });

    User user = context.getTypeConverter().convertTo(User.class, "seda:out"); // Here i need to access string from "seda:out"

    context.start();
    Thread.sleep(5000);
    System.out.println(user.getLogin());

}

private static class UserConverter extends TypeConverterSupport {

    @SuppressWarnings("unchecked")
    public <T> T convertTo(Class<T> type, Exchange exchange, Object value) {
        User user = new User();
        user.setLogin(String.valueOf(value.toString()));
        return (T) user;
    }
}
}

我的输出是seda:out,但我需要输出是字符串,即 in seda:out
如何才能做到这一点?

4

1 回答 1

0

不要使用 TypeConvertor,而是使用处理器。处理器应从骆驼交换中提取字符串并创建用户对象。您的路线应如下所示

from("ftp://Mike@localhost").to("file://someDirPath").marshal(xmlJsonFormat).process(
    new Processor() {
      public void process(Exchange exchange) throws Exception {
          String payload = exchange.getIn().getBody(String.class);
          // create the User object and set in  the body
          exchange.getIn().setBody(userObject);} });
于 2013-10-16T13:42:34.313 回答