将骆驼中的多个对象转换为XML文件

时间:2018-08-14 17:01:22

标签: java apache-camel

我想在Apache骆驼中将多个xml对象转换为json对象。但是我只能够转换单个对象。参考以下内容和附带的代码,我尝试了一些方法

  1. 在Employee类中创建ArrayList
  2. XMLToJSONRoute类中的
  3. ListJacksonDataFormat,但都不起作用。

有人可以指出我在做什么错吗?

Employee.class

@DataField(pos = 1)
private int empId;
@DataField(pos = 2)
private String empName;
@DataField(pos = 3)
private int sal;

// XMLElement
public String getEmpName() {
    return empName;
}

public void setEmpName(String empName) {
    this.empName = empName;
}

// XMLElement
public int getEmpId() {
    return empId;
}

public void setEmpId(int empId) {
    this.empId = empId;
}

主班

    XMLToJSONRoute routeBuilder = new XMLToJSONRoute();
    CamelContext ctx = new DefaultCamelContext();


    try {
        ctx.addRoutes(routeBuilder);
        ctx.start();
        Thread.sleep(5 * 60 * 1000);
        ctx.stop();

XMLtoJSON路由

@Override
public void configure() throws Exception {

    //JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
    //Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();       


    JaxbDataFormat xmlDataFormat = new JaxbDataFormat();                        
    //1.  XML Data Format
    JAXBContext con = JAXBContext.newInstance(Employee.class);
    xmlDataFormat.setContext(con);



    JacksonDataFormat jsonDataFormat = new JacksonDataFormat(Employee.class); 
     // 1. JSON Data Format
    //ListJacksonDataFormat jsonDataFormat2 = new ListJacksonDataFormat(Employee.class); // 1. JSON Data Format

    from("file:C:/inputFolder/.camel/xml?noop=true")
    .unmarshal(xmlDataFormat)
                    //.marshal().xstream()
    //Unmarshaled debug part 
    .process(new Processor(){

    //Unmarshaled debug part 

    .marshal(jsonDataFormat)
    .to("file:C:/outputFolder/json").
    // Marshalled output 
                process(new Processor(){
                    public void process(Exchange exchange) throws Exception {

                ;}


}

1 个答案:

答案 0 :(得分:0)

查看ListJacksonDataFormat的源代码,原因可能是(雇员Bean的)列表必须为java.util.ArrayList

public ListJacksonDataFormat() {
        useList();
    }

/**
 * Uses {@link java.util.ArrayList} when unmarshalling.
 */
public void useList() {
    setCollectionType(ArrayList.class);
}