0

I have String as:

String cont = "[[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,13.46,\"1682432\"]," +
                    "[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,-13.46,\"1682432\"]," +
                    "[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,-14.52,\"1682432\"]," +
                    "[\"START\",\"6002\",\"020\",\"0000000PWO\",\"2014-07-15\",\"MY Comment - FICA and\",-13.46,0,\"1682432\"]," +
                    "[\"START\",\"6002\",\"020\",\"0000000PWO\",\"2014-07-15\",\"MY Comment - FEED\",-1.06,0,\"1682432\"]" +
                "]";

I need output as

Account || Date ||        Amount || Description ||          InvoiceNo
1001     2014-07-15       -13.46                            1682432
....some more data
6002     2014-07-15       -1.06    MY desc                  1682432

I am trying to use Apache CSV parser with version 2.3.

<dependency>
    <groupId>net.sf.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>2.3</version>
</dependency>

java code:

CSVReader reader = new CSVReader(new StringReader(cont), ',');
List<String[]> records = reader.readAll();
Iterator<String[]> iterator = records.iterator();
while (iterator.hasNext()) {
    String[] record  =  iterator.next();
    for (String string : record) {
        System.out.println(string);
    }
}

output:

[[START 
1001  
2014-07-15

...

["START
6002
020
0000000PWO
2014-07-15
MY Comment - FEED
-1.06
0
1682432"]]

1) How do I remove the special character "[" and "]"

2) How do I assign values to above output fields

3) I want to convert above csv to bean object

4) bean to json

1
  • I think you're actually using opencsv. Yes, it happens to be under Apache license, but there is also Commons CSV which is the CSV library by The Apache Software Foundation. As a side note, I can warmly recommend Commons CSV. Commented Aug 14, 2014 at 19:11

5 Answers 5

1

You could utilize the open source library uniVocity-parsers to convert csv to bean objects, just as following code shows:

public static void main(String[] args) throws FileNotFoundException {
    /**
     * ---------------------------------------------
     *  Read CSV rows into list of beans you defined
     * ---------------------------------------------
     */
    // 1st, config the CSV reader with row processor attaching the bean definition
    BeanListProcessor<ColumnBean> rowProcessor = new BeanListProcessor<ColumnBean>(ColumnBean.class);
    settings.setRowProcessor(rowProcessor);
    settings.setHeaderExtractionEnabled(true);

    // 2nd, parse all rows from the CSV file into the list of beans you defined
    parser.parse(new StringReader(cont));
    List<ColumnBean> resolvedBeans = rowProcessor.getBeans();

    // 3rd, process the beans with business logic
    // ......
}

With the library, you only need several lines of code, and it also provides significent performance. Find tutorials at its Homepage.

As per the convert from bean object to json, you can check the Google Gson project.

Sign up to request clarification or add additional context in comments.

Comments

0

For 2), use System.out.print, instead of println (this just prints the string without a new line at the end), and concatenate tabs (\t) to your data values. You will need to break up your string variable into multiple parts to achieve this. Tabs will allow you to align them in proper rows appropriately.

Once your string is in multiple parts, for 1) you will want to slice the first character from the first "piece" and the last character from the last piece. This will remove the first [ and the last ]. I suggest using substring.

Comments

0

To remove the special characters I used a regexp for all special characters except "-" which you strings seems to contain. If more characters are to be kept , refactor that to a special set and just append it to the regexp.

For assigning values I'm not really sure what you want to do, I guess you want a String variable in the code for either a line or a ,ABCXYZ,. If you want to construct a string dynamically from a whole line use a StringBuilder or StringBuffer. I came up with this code for parsing

String cont = "[[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,13.46,\"1682432\"]," +
            "[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,-13.46,\"1682432\"]," +
            "[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,-14.52,\"1682432\"]," +
            "[\"START\",\"6002\",\"020\",\"0000000PWO\",\"2014-07-15\",\"MY Comment - FICA and\",-13.46,0,\"1682432\"]," +
            "[\"START\",\"6002\",\"020\",\"0000000PWO\",\"2014-07-15\",\"MY Comment - FEED\",-1.06,0,\"1682432\"]" +
            "]";

    CSVReader reader = new CSVReader(new StringReader(cont), ',');
    List<String[]> records = reader.readAll();
    Iterator<String[]> iterator = records.iterator();
    while (iterator.hasNext()) {
        String[] record = iterator.next();

        for (String string : record) {
            string = string.replaceAll("[^\\w\\s\\-]", "");
            if (string.startsWith("START")) {
                System.out.println();
            }
            System.out.print(string);
            System.out.print(",");
        }
    }

Comments

0

You no need to use any csv parser jars Just use the below code

public static void main(String arg[]) {
   String cont = "[[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,13.46,\"1682432\"]," +
                "[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,-13.46,\"1682432\"]," +
                "[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,-14.52,\"1682432\"]," +
                "[\"START\",\"6002\",\"020\",\"0000000PWO\",\"2014-07-15\",\"MY Comment - FICA and\",-13.46,0,\"1682432\"]," +
                "[\"START\",\"6002\",\"020\",\"0000000PWO\",\"2014-07-15\",\"MY Comment - FEED\",-1.06,0,\"1682432\"]" +
            "]";

    String[] csvArry = cont.split(",");      
    for (String value : csvArry) {
        value = value.replaceAll("[^\\w\\s\\-]", "");
        System.out.println(value); 
    }
}

It will do everything which you want. Hope this will resolve your issue.

Comments

0

For transformation of CSV to beans use https://github.com/CyborTronik/fluent-ssv

You are also able to write your line parser(where you will throw unecesary chars) by implementing LineParser and provide it to SsvStreamBuilder.

That's it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.