0

I'm using apache commons.csv.CSVparser. I want to use a String array in a csv record for instance:

"\"[\"54bb051e-3d12-11e5-91cd-b8f6b11b7feb\",\"472a9748-3d12-11e5-91cd-b8f6b11b7feb\"]\",Hallo,114058,Leon,31,\"     \",8400,bar,FOO";
        CSVParser csvParser = CSVFormat.DEFAULT
                .withDelimiter(CSV_SEPARATOR).withQuote(null)
                .withFirstRecordAsHeader()
                .parse(new StringReader(line));

How to escape the comma in the String[] array? After the record is readin the Strings get split into a java array.

I tried this:

@Test
    public void processLine() throws Exception {
        String line = "Ids,Info.name,Info.number,address.street,address.number,address.bus,address.postalcode,address.city," +
                "address.country\n" +
                "\"[\"\"54bb051e-3d12-11e5-91cd-b8f6b11b7feb\"\",\"\"472a9748-3d12-11e5-91cd-b8f6b11b7feb\"\"]\",Hallo,114058,Leon,31,\"     \",8400,foo,BAR";
        CSVParser csvParser = CSVFormat.DEFAULT
                .withDelimiter(CSV_SEPARATOR).withQuote(null)
                .withFirstRecordAsHeader()
                .parse(new StringReader(line));

The comma of the String[] still been seen as a delimiter.

2
  • 1
    you can use replace("," "") Commented May 9, 2018 at 9:50
  • The comma doesn't need to be replaced in the csv record. The comma is mandatory there. My question is how to escape the comma here [\"54bb051e-3d12-11e5-91cd-b8f6b11b7feb\",\"472a9748-3d12-11e5-91cd-b8f6b11b7feb\"] so that the parser doesn't treat it as a delimiter. Commented May 9, 2018 at 9:56

2 Answers 2

1

You need to escape correctly the CSV content. Try this out: "\"[\"\"54bb051e-3d12-11e5-91cd-b8f6b11b7feb\"\",\"\"472a9748-3d12-11e5-91cd-b8f6b11b7feb\"\"]\",Hallo,114058,Leon,31,\" \",8400,bar,FOO"

The escaping gets confuse because you mix Java and CSV. While in java you need to user \" to escape the double quotes, on CSV you need double-double quotes to escape it. At the end you need a \"\" to get the output "" on string. The final string would look like: "[""54bb051e-3d12-11e5-91cd-b8f6b11b7feb"",""472a9748-3d12-11e5-91cd-b8f6b11b7feb""]",Hallo,114058,Leon,31," ",8400,bar,FOO. Being the first value on the CSV: ["54bb051e-3d12-11e5-91cd-b8f6b11b7feb","472a9748-3d12-11e5-91cd-b8f6b11b7feb"]

Additionally your string doesn't contain header, so you need to take care with withFirstRecordAsHeader().

This:

CSVParser csvParser = CSVFormat.DEFAULT.withDelimiter(',').withQuote('"').parse(new StringReader(
        "\"[\"\"54bb051e-3d12-11e5-91cd-b8f6b11b7feb\"\",\"\"472a9748-3d12-11e5-91cd-b8f6b11b7feb\"\"]\",Hallo,114058,Leon,31,\"     \",8400,bar,FOO"));
System.out.println(csvParser.getRecords().get(0).get(0));

Will output the following string:

["54bb051e-3d12-11e5-91cd-b8f6b11b7feb","472a9748-3d12-11e5-91cd-b8f6b11b7feb"]

And this string can be used be parsed into a String[].

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

3 Comments

Still no success.
Working now! Tnx!
@JoVanMontfort Here is what to do when someone answers your question. To mark an answer as accepted, click on the check mark ✔ beside the answer to toggle it from greyed out to filled in. There is no need to add a comment on your question or on an answer to say "Thank you".
0

You should not generate your own CSV line for testing, you already have the library to create it properly. You had the idea to use the Apache Commons to read the CSV but not to create it.

Using a CSVPrinter will "escape" the delimiter if needed(by escape, it will you double quotes the values as the format allows it)

//Get a printer on the System.out
CSVPrinter printer = CSVFormat.DEFAULT.withHeader("A", "B").printer();
// Create the pojos
List<POJO> pojos = new ArrayList<>();
pojos.add(new POJO("foo", "bar"));
pojos.add(new POJO("far", "boo"));
pojos.add(new POJO("for", "bao"));
pojos.add(new POJO("test,", "comma"));

for(POJO p : pojos) {
    printer.printRecord(p.a, p.b);
}

A,B
foo,bar
far,boo
for,bao
"test,",comma

Using the POJO class

public class POJO{
    String a;
    String b;

    public POJO(String a, String b) {
        this.a = a;
        this.b = b;
    }

    @Override
    public String toString() {
        return "POJO [a=" + a + " ## b=" + b + "]";
    }
}

Note : this is probably not the perfect usage of the library, I have only used it once (now) but this is to show you that this can/should be done using the API instead of creating your own "CSV" line

And to show that this will be recovered correctly, let use an Appendable to store the CSV :

StringBuffer sb = new StringBuffer();
CSVPrinter printer = CSVFormat.DEFAULT.withHeader("A", "B").print(sb);
List<POJO> pojos = new ArrayList<>();
pojos.add(new POJO("foo", "bar"));
pojos.add(new POJO("far", "boo"));
pojos.add(new POJO("for", "bao"));
pojos.add(new POJO("test,", "comma"));

for(POJO p : pojos) {
    printer.printRecord(p.a, p.b);
}

System.out.println("PRINTER");
System.out.println(sb.toString());

PRINTER
A,B
foo,bar
far,boo
for,bao
"test,",comma

And parse that String and create the POJO back :

CSVParser parser = CSVFormat.DEFAULT
                .withFirstRecordAsHeader()
                .parse(new StringReader(sb.toString()));

System.out.println("PARSER");
parser.getRecords().stream().map(r -> new POJO(r.get(0), r.get(1))).forEach(System.out::println);

PARSER
POJO [a=foo ## b=bar]
POJO [a=far ## b=boo]
POJO [a=for ## b=bao]
POJO [a=test, ## b=comma

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.