user4975679
user4975679

Reputation: 1589

Jackson CSV's WRAP_AS_ARRAY

According to http://fasterxml.github.io/jackson-dataformat-csv/javadoc/2.0.0/com/fasterxml/jackson/dataformat/csv/CsvParser.Feature.html, WRAP_AS_ARRAY is:

Feature that determines how stream of records (usually CSV lines, but sometimes multiple lines when linefeeds are included in quoted values) is exposed: either as a sequence of Objects (false), or as an array of Objects (true).

What is the difference between a "sequence of Objects" and an "array of Objects"? The description seems the same to me.

Upvotes: 1

Views: 2352

Answers (1)

araqnid
araqnid

Reputation: 133582

Parsing to a sequence of objects: you call readValues() and get a MappingIterator, which gives you the objects one-by-one. Equivalent to input containing multiple JSON objects, one after the other.

Parsing to an array of objects: you call readValue() and get a List of the objects. Equivalent to input containing a JSON array.

Examples:

@Test
public void parses_csv_to_object_list() throws Exception {
    String csv = "id,name\n1,Red\n2,Green\n3,Blue";
    CsvMapper mapper = new CsvMapper();
    CsvSchema schema = mapper.schemaFor(ColourData.class).withHeader();
    ObjectReader reader = mapper.readerFor(ColourData.class).with(schema);
    try (MappingIterator<ColourData> iter = reader.readValues(csv)) {
        assertThat(iter.readAll(),
                contains(new ColourData(1, "Red"), new ColourData(2, "Green"), new ColourData(3, "Blue")));
    }
}

@Test
public void parses_csv_to_object_list_in_one_read() throws Exception {
    String csv = "id,name\n1,Red\n2,Green\n3,Blue";
    CsvMapper mapper = new CsvMapper().enable(CsvParser.Feature.WRAP_AS_ARRAY);
    CsvSchema schema = mapper.schemaFor(ColourData.class).withHeader();
    ObjectReader reader = mapper.readerFor(new TypeReference<List<ColourData>>() {
    }).with(schema);
    assertThat(reader.readValue(csv),
            contains(new ColourData(1, "Red"), new ColourData(2, "Green"), new ColourData(3, "Blue")));
}

Upvotes: 3

Related Questions