Convert csv to json java

directly convert CSV file to JSON file using the Jackson library

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 Answer 1

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> data = readObjectsFromCsv(input); writeAsJson(data, output); > public static List> readObjectsFromCsv(File file) throws IOException < CsvSchema bootstrap = CsvSchema.emptySchema().withHeader(); CsvMapper csvMapper = new CsvMapper(); try (MappingIterator> mappingIterator = csvMapper.readerFor(Map.class).with(bootstrap).readValues(file)) < return mappingIterator.readAll(); >> public static void writeAsJson(List> data, File file) throws IOException < ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(file, data); >> 

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

Источник

Converting an CSV file to a JSON object in Java

Is there an open source java library to convert a CSV (or XLS) file to a JSON object? I tried using json.cdl, but somehow it does not seem to work for large CSV strings. I’m trying to find something like http://www.cparker15.com/code/utilities/csv-to-json/, but written in Java.

Читайте также:  Php coercible for operation

OpenCSV is a pretty good library for working with .csv’s: baeldung.com/opencsv — you can use it to get a POJO from a file and then serialize it into another format fairly easily.

9 Answers 9

You can use Open CSV to map CSV to a Java Bean, and then use JAXB to convert the Java Bean into a JSON object.

Here is my Java program and hope somebody finds it useful.

Format needs to be like this:

First line is the column headers. No quotation marks anywhere. Separate with commas and not semicolons. You get the deal.

/* Summary: Converts a CSV file to a JSON file.*/ //import java.util.*; import java.io.*; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; public class CSVtoJSON extends JFrame < private static final long serialVersionUID = 1L; private static File CSVFile; private static BufferedReader read; private static BufferedWriter write; public CSVtoJSON()< FileNameExtensionFilter filter = new FileNameExtensionFilter("comma separated values", "csv"); JFileChooser choice = new JFileChooser(); choice.setFileFilter(filter); //limit the files displayed int option = choice.showOpenDialog(this); if (option == JFileChooser.APPROVE_OPTION) < CSVFile = choice.getSelectedFile(); >else < JOptionPane.showMessageDialog(this, "Did not select file. Program will exit.", "System Dialog", JOptionPane.PLAIN_MESSAGE); System.exit(1); >> public static void main(String args[]) < CSVtoJSON parse = new CSVtoJSON(); parse.convert(); System.exit(0); >private void convert() < /*Converts a .csv file to .json. Assumes first line is header with columns*/ try < read = new BufferedReader(new FileReader(CSVFile)); String outputName = CSVFile.toString().substring(0, CSVFile.toString().lastIndexOf(".")) + ".json"; write = new BufferedWriter(new FileWriter(new File(outputName))); String line; String columns[]; //contains column names int num_cols; String tokens[]; int progress = 0; //check progress //initialize columns line = read.readLine(); columns = line.split(","); num_cols = columns.length; write.write("["); //begin file as array line = read.readLine(); while(true) < tokens = line.split(","); if (tokens.length == num_cols)< //if number columns equal to number entries write.write("<"); for (int k = 0; k < num_cols; ++k)< //for each column if (tokens[k].matches("^-?4*\\.?6*$"))< //if a number write.write("\"" + columns[k] + "\": " + tokens[k]); if (k < num_cols - 1) write.write(", "); >else < //if a string write.write("\"" + columns[k] + "\": \"" + tokens[k] + "\""); if (k < num_cols - 1) write.write(", "); >> ++progress; //progress update if (progress % 10000 == 0) System.out.println(progress); //print progress if((line = read.readLine()) != null),"); write.newLine(); > else< write.write(">]");//if last line write.newLine(); break; > > else < //line = read.readLine(); //read next line if wish to continue parsing despite error JOptionPane.showMessageDialog(this, "ERROR: Formatting error line " + (progress + 2) + ". Failed to parse.", "System Dialog", JOptionPane.PLAIN_MESSAGE); System.exit(-1); //error message >> JOptionPane.showMessageDialog(this, "File converted successfully to " + outputName, "System Dialog", JOptionPane.PLAIN_MESSAGE); write.close(); read.close(); > catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> > 

Requires Swing but comes with a nifty little GUI so those who know absolutely no Java can use it once packaged into an executable .jar. Feel free to improve upon it. Thank you StackOverflow for helping me out all these years.

Источник

Как преобразовать CSV в JSON в Java

конвертировать CSV в JSON в Java

Загрузите файл CSV, обработайте его данные и преобразуйте их в формат JSON (JavaScript Object Notation) программным путем. В наш век технологий большинство API-интерфейсов предпочитают взаимодействовать в формате JSON, потому что JSON легко анализировать, он легкий и компактный. В этом сообщении блога мы узнаем, как преобразовать CSV в JSON на Java с помощью библиотеки Java Excel. Эта библиотека проста в установке и предлагает широкий спектр методов для преобразования CSV в JSON.

В этой статье мы рассмотрим следующие моменты:

Установка API преобразования CSV в JSON#

Мы собираемся интегрировать эту Java Excel библиотеку с приложением на основе Java. Доступна исчерпывающая документация относительно установки и использования.

Однако вы можете либо загрузить файлы JAR, либо следовать следующим конфигурациям Maven:

 AsposeJavaAPI Aspose Java API https://repository.aspose.com/repo/  
 com.aspose aspose-cells 22.6  

Как преобразовать CSV в JSON в Java#

После завершения процесса установки мы можем перейти к фрагменту кода, который программно преобразует файл CSV в формат JSON. На самом деле, автоматизация этого процесса преобразования даст бизнес-приложению конкурентное преимущество.

Мы выполним следующие шаги:

  1. Создайте объект класса LoadOptions, представляющий параметры загрузки файла.
  2. Загрузите файл CSV, инициировав экземпляр класса Workbook.
  3. Получите доступ к последней ячейке листа, вызвав метод getLastCell.
  4. Установите ExportRangeToJsonOptions, чтобы указать параметры, которые экспортируют диапазон в JSON.
  5. Метод createRange создает объект диапазона из диапазона ячеек.
  6. Экспортируйте диапазон в файл JSON, вызвав метод exportRangeToJson.
  7. Вызовите метод save, чтобы сохранить JSON в файл.
// Создайте объект класса LoadOptions, представляющий параметры загрузки файла. LoadOptions loadOptions = new LoadOptions(LoadFormat.CSV); // Загрузите файл CSV, инициировав экземпляр класса Workbook. Workbook workbook = new Workbook( "sample.csv", loadOptions); // получить доступ к последней ячейке листа, вызвав метод getLastCell. Cell lastCell = workbook.getWorksheets().get(0).getCells().getLastCell(); // Установите ExportRangeToJsonOptions, чтобы указать параметры, которые экспортируют диапазон в json. ExportRangeToJsonOptions options = new ExportRangeToJsonOptions(); // Метод createRange создает объект диапазона из диапазона ячеек. Range range = workbook.getWorksheets().get(0).getCells().createRange(0, 0, lastCell.getRow() + 1, lastCell.getColumn() + 1); // экспортировать диапазон в файл json, вызвав метод exportRangeToJson. String data = JsonUtility.exportRangeToJson(range, options); // Вызовите метод сохранения, чтобы сохранить JSON в файле. workbook.save("Output.json"); 

Вы можете увидеть результат на изображении ниже:

Преобразование CSV в JSON

Получить бесплатную лицензию#

Вы можете получить бесплатную временную лицензию, чтобы опробовать API за рамками ознакомительных ограничений.

Подведение итогов#

Это подводит нас к концу этого сообщения в блоге. Мы узнали, как программно конвертировать CSV в JSON на Java. Мы также написали фрагмент кода, в котором использовали некоторые методы API. Кроме того, вы можете посетить документацию этой библиотеки Java Excel, чтобы узнать о других функциях. Кроме того, вы можете найти некоторые другие соответствующие ссылки в разделе «См. также» ниже. Наконец, посетите conholdate.com для получения последних обновлений.

Задайте вопрос#

Вы можете сообщить нам о своих вопросах или запросах на нашем форуме.

Часто задаваемые вопросы#

Можете ли вы преобразовать CSV в JSON?

Используя эту библиотеку Java Excel, вы можете программно преобразовать CSV в JSON в приложении Java.

Какую библиотеку можно использовать для обработки документа Excel?

Установите эту Java Excel библиотеку для обработки и преобразования документов Excel в другие популярные форматы файлов, такие как PDF, PPT и другие.

Как импортировать файл CSV в JSON?

Используйте этот метод JsonUtility.exportRangeToJson(range, options) для программного преобразования файла CSV в формат JSON. Кроме того, вы также можете посетить документацию, чтобы узнать о других методах.

Смотрите также#

Источник

How to Convert CSV to JSON in Java

Join the DZone community and get the full member experience.

CSV to JSON conversion is easy. In this article, we present a couple of methods to parse CSV data and convert it to JSON. The first method defines a POJO and uses simple string splitting to convert CSV data to a POJO, which, in turn, is serialized to JSON. The second method uses a more complete CSV parser with support for quoted fields and commas embedded within fields. In this method, we use the Java Collection classes to store the parsed data and convert those to JSON.

We use Jackson for the JSON conversion.

CSV data

Simple CSV Parsing

When the CSV file to be parsed is simple (there are no quoted fields or commas embedded in fields), you can use a simple pattern matcher to split the CSV fields.

Pattern pattern = Pattern.compile(",");

POJO Definition

We are going to parse the CSV data and create the POJO (Plain-Old-Java-Object) shown in this definition.

public class Player < private int year; private String teamId; private String leagueId; private String playerId; private int salary; public Player(int year, String teamId, String leagueId, String playerId, int salary) < this.year = year; this.teamId = teamId; this.leagueId = leagueId; this.playerId = playerId; this.salary = salary; >// getters and setters here >;

Reading the CSV Data

Open the CSV file using a BufferedReader in a try-with-resources block.

try (BufferedReader in = new BufferedReader(new FileReader(csvFile));) < // processing code here >

Create the List of POJOs using a streaming pipeline. The first line is skipped because it is the CSV header. The line is split into fields using the Pattern, converted to appropriate types and used to create the object.

List players = in .lines() .skip(1) .map(line -> < String[] x = pattern.split(line); return new Player(Integer.parseInt(x[0]), x[1], x[2], x[3], Integer.parseInt(x[4])); >) .collect(Collectors.toList());

Serialize to JSON

Once the List is ready, use Jackson’s ObjectMapper to write the JSON. Check for full details on JSON serialization and deserialization.

ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.writeValue(System.out, players);

And here is the whole programs segment.

Pattern pattern = Pattern.compile(","); try (BufferedReader in = new BufferedReader(new FileReader(csvFile));) < List < Player >players = in .lines().skip(1).map(line - > < String[] x = pattern.split(line); return new Player(Integer.parseInt(x[0]), x[1], x[2], x[3], Integer.parseInt(x[4])); >).collect(Collectors.toList()); ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.writeValue(System.out, players); >

CSV to JSON Conversion (No POJO)

In this example, we use the CSV parser presented in this article. This CSV parser can handle multi-line quoted fields and commas embedded within fields, just like Excel can. It uses the first line of the CSV file as field names and loads the data into a List, which is then exported to JSON.

Here is the complete segment.

try (InputStream in = new FileInputStream(csvFile);) < CSV csv = new CSV(true, ',', in ); List < String >fieldNames = null; if (csv.hasNext()) fieldNames = new ArrayList < >(csv.next()); List < Map < String, String >> list = new ArrayList < >(); while (csv.hasNext()) < List < String >x = csv.next(); Map < String, String >obj = new LinkedHashMap < >(); for (int i = 0; i < fieldNames.size(); i++) < obj.put(fieldNames.get(i), x.get(i)); >list.add(obj); > ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); mapper.writeValue(System.out, list); >

Here is a part of the CSV data that was converted:

rep_file_num,CIK,entity_name,street1,street2,city,state_code,zip,filing_date,doc_type_code 814-00034,0000731812,SIERRA RESOURCES CORP,629 J STREET,SUITE 202,SACRAMENTO,CA,95814,12/30/96,15 814-00053,0000821472,WESTFORD TECHNOLOGY VENTURES LP,17 ACADEMY ST 5TH FLOOR,[NULL],NEWARK,NJ,07102-2905,01/28/04,NO ACT . 814-00098,0000878932,"EQUUS TOTAL RETURN, INC.",EIGHT GREENWAY PLAZA,SUITE 930,HOUSTON,TX,77046,08/25/16,40-APP/A

Notice that one of the fields in the data is quoted because of embedded commas. Here is the converted JSON for that record, which shows that the record has been parsed and converted correctly.

Summary

CSV data can be converted to JSON via a POJO using Jackson. If a POJO is not already defined or required, you can always use the Java Collection classes to store parsed data and later convert it to JSON.

Published at DZone with permission of Jay Sridhar , DZone MVB . See the original article here.

Opinions expressed by DZone contributors are their own.

Источник

Оцените статью