简体   繁体   中英

How to convert csv to json in apache camel

I able to convert csv into pojo with the help of camel bindy. But I need to convert the string to json easily?

I able to do my splitting the string.But is there any efficient methods to do it?

My pojo Class:-

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

public class Sample
{

 //some fields

}

Processor Class:-

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

Route Builder:-

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");

    }
}

Eager to know if there is any efficient method to solve this?

.json()

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

In your scenario for example:

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");

where json(JsonLibrary.Jackson) forces the use of the jackson library for the conversion.

  1. You can use camel bindy t unmarshal csv to List of POJO
  2. Do mapping if required base on output format
  3. marshal mapped data using Jacson o Gson in Came route.
    from("file:/input/path/?noop=true")
    .unmarshal(bindy)
    .marshal()
    .json(JsonLibrary.Jackson).log("${body}")
    .to("file:/path/?fileName=test.txt");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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