【问题标题】:How to convert csv to json in apache camel如何在apache骆驼中将csv转换为json
【发布时间】:2019-04-30 22:40:39
【问题描述】:

我可以在 camel bindy 的帮助下将 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");

    }
}

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

【问题讨论】:

    标签: java apache-camel


    【解决方案1】:

    .json()

    camel json data format 即:.json().log("${body}")

    以您的场景为例:

    from("file:/path/?fileName=CCO_SUMMARY_20190315_165800 copy.csv&noop=true")
        .unmarshal(bindy)
        .marshal()
        .json(JsonLibrary.Jackson).log("${body}")
        .to("file:/path/?fileName=akshay.txt");
    

    json(JsonLibrary.Jackson) 强制使用 jackson 库进行转换。

    【讨论】:

    • 感谢您的评论。这很有帮助。我卡在主方法中。我在主方法中有 Thread.sleep(5000)。CamelContext camelContext=new DefaultCamelContext(); SimpleRouteBuilder simpleBuilder=new SimpleRouteBuilder();尝试 { camelContext.addRoutes(simpleBuilder); camelContext.start(); //Thread.sleep(1000);如何摆脱这个 Thread.sleep 并在完成后停止路由。
    • 我从未单独使用过它,但是您可以找到文档camel.apache.org/… 和在线示例github.com/apache/camel/blob/master/core/camel-core/src/test/… apache 站点中的大多数示例都已损坏,但您可以在以下位置找到graal:github.com/apache/camel 如果您正在使用弹簧靴camel.apache.org/spring-boot.html
    【解决方案2】:
    1. 您可以使用camel bindy t unmarshal csv to List of POJO
    2. 如果需要,根据输出格式进行映射
    3. 在 Came 路线中使用 Jacson o Gson 编组映射数据。
    从(“文件:/输入/路径/?noop = true”) .unmarshal(绑定) 。元帅() .json(JsonLibrary.Jackson).log("${body}") .to("file:/path/?fileName=test.txt");

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 2020-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多