12

I am using following code:

CsvSchema bootstrap = CsvSchema.emptySchema().withHeader();
ObjectMapper mapper = new CsvMapper();
File csvFile = new File("input.csv"); // or from String, URL etc
Object user = mapper.reader(?).withSchema(bootstrap).readValue(new File("data.csv"));
mapper.writeValue(new File("data.json"), user);

It throws an error in my IDE saying cannot find symbol method withSchema(CsvSchema) but why? I have used the code from some examples.

I don't know what to write into mapper.reader() as I want to convert any CSV file.
How can I convert any CSV file to JSON and save it to the disk?

What to do next? The examples

1 Answers1

30

I think, you should use MappingIterator to solve your problem. See below example:

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

public class JacksonProgram {

    public static void main(String[] args) throws Exception {
        File input = new File("/x/data.csv");
        File output = new File("/x/data.json");

        List<Map<?, ?>> data = readObjectsFromCsv(input);
        writeAsJson(data, output);
    }

    public static List<Map<?, ?>> readObjectsFromCsv(File file) throws IOException {
        CsvSchema bootstrap = CsvSchema.emptySchema().withHeader();
        CsvMapper csvMapper = new CsvMapper();
        try (MappingIterator<Map<?, ?>> mappingIterator = csvMapper.readerFor(Map.class).with(bootstrap).readValues(file)) {
            return mappingIterator.readAll();
        }
    }

    public static void writeAsJson(List<Map<?, ?>> data, File file) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(file, data);
    }
}

See this page: jackson-dataformat-csv for more information and examples.

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • but where does this User.class come from? I am using the scheme from the first line of each CSV file so the User.class does not exist and is also not needed? –  Nov 04 '13 at 11:18
  • and then converting to JSON? This is just the part to read/parse CSV –  Nov 04 '13 at 11:19
  • I thought you have User class or something like that. Let me think about that. – Michał Ziober Nov 04 '13 at 11:23
  • No, I want to convert it directly to a JSON file and save it on the disk. –  Nov 04 '13 at 11:26
  • 2
    Yes, you can do this with `mapper.configure(SerializationFeature.INDENT_OUTPUT, true);` or with `mapper.writerWithDefaultPrettyPrinter().writeValue(file, data);` – Michał Ziober Nov 04 '13 at 12:42
  • 1
    Hi, can we inverse the process , from jsonObject to csv , using the same library ? – Ussopokingo Dec 03 '19 at 10:54
  • @Ussopokingo, yes, we can do that using [jackson-dataformats-text](https://github.com/FasterXML/jackson-dataformats-text/tree/master/csv). Take a look at [Parsing JSON with a random field (java)](https://stackoverflow.com/questions/55577959/parsing-json-with-a-random-field-java) – Michał Ziober Dec 03 '19 at 10:57
  • `mapper.reader(Map.class).with(bootstrap).readValues(destination);` is deprecated – G. Ciardini Jun 24 '22 at 20:42
  • WriteAsJson is returning null, able to read the file but it is not converting – Raj Aug 25 '22 at 08:09
  • @X_R86, what is the input `CSV` data? – Michał Ziober Aug 25 '22 at 11:41
  • @MichałZiober Test_Scenario~Test_Case~Step_No~Status~Description~Detailed Description~Expected_Data~Actual_Data~Execution_Date~Execution_Time~Error_Screenshot~LastWebPage GreenMile~GM_Login~~Pass~~~~~08_24_2022~0:0:6~~ – Raj Aug 25 '22 at 13:08
  • @X_R86, do you use `~` as a separator between columns? – Michał Ziober Aug 25 '22 at 16:07
  • @MichałZiober yes – Raj Aug 25 '22 at 16:23
  • @X_R86, have you tried to configure `CsvSchema` to use this separator? `CsvSchema bootstrap = CsvSchema.emptySchema().withHeader().withColumnSeparator('~');` – Michał Ziober Aug 25 '22 at 16:35
  • @MichałZiober I tried still giving parse error, JsonParseException: Unexpected character (',' (code 44)): like this – Raj Aug 25 '22 at 19:04
  • @MichałZiober https://codeshare.io/LwoKze this is my csv file text – Raj Aug 25 '22 at 19:29
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/247580/discussion-between-michal-ziober-and-x-r86). – Michał Ziober Aug 26 '22 at 09:00