/
siman_coder
/
CSVXML-JSON
Обзор
Документация
Войти
/
siman_coder
/
CSVXML-JSON
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Main.java
187 строк
7 KB
siman_coder
Create: Main.java, Employee.java, build.gradle, data.csv, data.json, data.xml, data2.json
07 июл 2026, 10:35
Верифицирован
07 июл 2026, 10:35
c41a7e2
Код
Авторство
О чём код?
package org.example; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.opencsv.CSVReader; import com.opencsv.bean.ColumnPositionMappingStrategy; import com.opencsv.bean.CsvToBean; import com.opencsv.bean.CsvToBeanBuilder; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Type; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { System.out.println("=== Задача 1: CSV -> JSON ==="); String[] columnMapping = {"id", "firstName", "lastName", "country", "age"}; String csvFileName = "data.csv"; List<Employee> csvList = parseCSV(columnMapping, csvFileName); if (csvList != null && !csvList.isEmpty()) { String jsonFromCsv = listToJson(csvList); writeString(jsonFromCsv, "data.json"); System.out.println("CSV -> JSON успешно создан!"); } System.out.println("\n=== Задача 2: XML -> JSON ==="); String xmlFileName = "data.xml"; List<Employee> xmlList = parseXML(xmlFileName); if (xmlList != null && !xmlList.isEmpty()) { String jsonFromXml = listToJson(xmlList); writeString(jsonFromXml, "data2.json"); System.out.println("XML -> JSON успешно создан!"); } System.out.println("\n=== Задача 3: JSON -> Java ==="); String jsonFileName = "data.json"; List<Employee> employeesFromJson = jsonToList(jsonFileName); if (employeesFromJson != null && !employeesFromJson.isEmpty()) { System.out.println("Парсинг JSON в Java объекты:"); for (Employee emp : employeesFromJson) { System.out.println(emp); } String outputJson = listToJson(employeesFromJson); writeString(outputJson, "output.json"); System.out.println("Результат сохранен в output.json"); } } public static List<Employee> parseCSV(String[] columnMapping, String fileName) { List<Employee> employees = null; try (CSVReader csvReader = new CSVReader(new FileReader(fileName))) { ColumnPositionMappingStrategy<Employee> strategy = new ColumnPositionMappingStrategy<>(); strategy.setType(Employee.class); strategy.setColumnMapping(columnMapping); CsvToBean<Employee> csvToBean = new CsvToBeanBuilder<Employee>(csvReader) .withMappingStrategy(strategy) .build(); employees = csvToBean.parse(); System.out.println("Прочитано " + employees.size() + " записей из CSV"); } catch (IOException e) { System.err.println("Ошибка при чтении CSV: " + e.getMessage()); e.printStackTrace(); } return employees; } public static List<Employee> parseXML(String fileName) { List<Employee> employees = new ArrayList<>(); try { // Читаем XML файл String xmlContent = new String(Files.readAllBytes(Paths.get(fileName))); System.out.println("XML содержимое:"); System.out.println(xmlContent); // Разбиваем на отдельные записи employee String[] parts = xmlContent.split("</employee>"); for (String part : parts) { if (part.contains("<employee>")) { String idStr = extractTagContent(part, "id"); String firstName = extractTagContent(part, "firstName"); String lastName = extractTagContent(part, "lastName"); String country = extractTagContent(part, "country"); String ageStr = extractTagContent(part, "age"); if (idStr != null && firstName != null && lastName != null && country != null && ageStr != null) { long id = Long.parseLong(idStr.trim()); int age = Integer.parseInt(ageStr.trim()); Employee employee = new Employee(id, firstName, lastName, country, age); employees.add(employee); System.out.println("Добавлен сотрудник: " + employee); } } } System.out.println("Прочитано " + employees.size() + " записей из XML"); } catch (Exception e) { System.err.println("Ошибка при чтении XML: " + e.getMessage()); e.printStackTrace(); } return employees; } private static String extractTagContent(String xml, String tag) { String openTag = "<" + tag + ">"; String closeTag = "</" + tag + ">"; int startIndex = xml.indexOf(openTag); if (startIndex == -1) { return null; } startIndex += openTag.length(); int endIndex = xml.indexOf(closeTag, startIndex); if (endIndex == -1) { return null; } return xml.substring(startIndex, endIndex).trim(); } public static String listToJson(List<Employee> list) { GsonBuilder builder = new GsonBuilder().setPrettyPrinting(); Gson gson = builder.create(); Type listType = new TypeToken<List<Employee>>() {}.getType(); return gson.toJson(list, listType); } public static List<Employee> jsonToList(String fileName) { List<Employee> employees = new ArrayList<>(); try { String jsonContent = new String(Files.readAllBytes(Paths.get(fileName))); Gson gson = new Gson(); Type listType = new TypeToken<List<Employee>>() {}.getType(); employees = gson.fromJson(jsonContent, listType); System.out.println("Распаршено " + employees.size() + " объектов из JSON"); } catch (IOException e) { System.err.println("Ошибка чтении JSON: " + e.getMessage()); e.printStackTrace(); } return employees; } public static void writeString(String json, String fileName) { try (FileWriter fileWriter = new FileWriter(fileName)) { fileWriter.write(json); System.out.println("Файл " + fileName + " успешно создан"); } catch (IOException e) { System.err.println("Ошибка при записи файла: " + e.getMessage()); e.printStackTrace(); } } }