猿问

如何在 apache camel 中将 csv 转换为 json

我能够在骆驼绑定的帮助下将 csv 转换为 pojo。但我需要轻松地将字符串转换为 json 吗?


我可以拆分字符串。但是有什么有效的方法可以做到吗?


我的pojo类:-


@CsvRecord(separator = ",",skipFirstLine = true)


public class Sample

{


 //some fields


}

处理器类:-


String samples=exchange.getIn().getBody(String.class);


String[] strings=samples.split("}");

System.out.println(strings[0]);

for(String strings1:strings)

{

    String[] strings2=strings1.split("'");

    for(int i=0;i<strings2.length;i++)

    {

        if(i%2==1) {

            System.out.println(strings2[i]);

        }

    }

}

//Is there is efficient method we can do to convert the String to list of json. Assuming csv contains multiple record

路线建设者: -


public class SimpleRouteBuilder extends RouteBuilder {

    private final BindyCsvDataFormat bindy=new BindyCsvDataFormat(com.company.model.Sample.class);;

    @Override

    public void configure()  {


      from("file:/path/?fileName=CCO_SUMMARY_20190315_165800 copy.csv&noop=true").unmarshal(bindy).process(new MyProcessor()).

               to("file:/path/?fileName=akshay.txt");


    }

}

想知道是否有任何有效的方法来解决这个问题?


慕仙森
浏览 220回答 2
2回答

红糖糍粑

.json()请参阅骆驼 json 数据格式,&nbsp;即:.json().log("${body}")例如,在您的场景中:from("file:/path/?fileName=CCO_SUMMARY_20190315_165800&nbsp;copy.csv&noop=true") &nbsp;&nbsp;&nbsp;&nbsp;.unmarshal(bindy) &nbsp;&nbsp;&nbsp;&nbsp;.marshal() &nbsp;&nbsp;&nbsp;&nbsp;.json(JsonLibrary.Jackson).log("${body}") &nbsp;&nbsp;&nbsp;&nbsp;.to("file:/path/?fileName=akshay.txt");wherejson(JsonLibrary.Jackson)强制使用 jackson 库进行转换。

白板的微信

您可以使用 camel bindy t unmarshal csv to List of POJO如果需要,根据输出格式进行映射在 Came 路线中使用 Jacson o Gson 编组映射数据。&nbsp;从(“文件:/输入/路径/?noop = true”)&nbsp; &nbsp; .unmarshal(绑定)&nbsp; &nbsp; 。元帅()&nbsp; &nbsp; .json(JsonLibrary.Jackson).log("${body}")&nbsp; &nbsp; .to("file:/path/?fileName=test.txt");
随时随地看视频慕课网APP

相关分类

Java
我要回答