/
SofiMut
/
jsonConverterMaven
Обзор
Документация
Войти
/
SofiMut
/
jsonConverterMaven
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/main/java/Main.java
149 строк
5 KB
Sofia Stepanova
first_commit
08 окт 2025, 16:22
08 окт 2025, 16:22
35e7d31
Код
Авторство
О чём код?
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonParser; 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 org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.lang.reflect.Type; import java.text.ParseException; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, ParseException { String[] columnMapping = {"id", "firstName", "lastName", "country", "age"}; // CSV => JSON String fileName = "data.csv"; List<Employee> list = parseCSV(columnMapping, fileName); String json = listToJson(list); String jsonFile = "data.json"; writeString(json, jsonFile); // XML => JSON String xmlFile = "data.xml"; List<Employee> list2 = parseXML(xmlFile); String json2 = listToJson(list2); String jsonFile2 = "data2.json"; writeString(json2, jsonFile2); // read JSON String newFileName = "new_data.json"; List<Employee> list3 = parseCSV(columnMapping, fileName); String json3 = listToJson(list3); writeString(json3, newFileName); list3 = jsonToList(json3, newFileName); readString(newFileName); list3.forEach(System.out::println); } private static List<Employee> parseCSV(String[] columnMapping, String fileName) { try (CSVReader csvReader = new CSVReader(new FileReader(fileName))) { ColumnPositionMappingStrategy<Employee> strategy = new ColumnPositionMappingStrategy<>(); strategy.setType(Employee.class); strategy.setColumnMapping(columnMapping); CsvToBean<Employee> csv = new CsvToBeanBuilder<Employee>(csvReader) .withMappingStrategy(strategy) .build(); return csv.parse(); } catch (IOException e) { e.printStackTrace(); } return null; } private static String listToJson(List<Employee> list) { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.setPrettyPrinting().create(); Type listType = new TypeToken<List<Employee>>() { }.getType(); return gson.toJson(list, listType); } private static void writeString(String json, String jsonFile) { try (FileWriter file = new FileWriter(jsonFile)) { file.write(json); file.flush(); } catch (IOException e) { e.printStackTrace(); } } private static List<Employee> parseXML(String xmlFile) throws ParserConfigurationException, IOException, SAXException { List<String> elements = new ArrayList<>(); List<Employee> list = new ArrayList<>(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new File(xmlFile)); Node root = doc.getDocumentElement(); NodeList nodeList = root.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeName().equals("employee")) { NodeList nodeList1 = node.getChildNodes(); for (int j = 0; j < nodeList1.getLength(); j++) { Node node_ = nodeList1.item(j); if (Node.ELEMENT_NODE == node_.getNodeType()) { elements.add(node_.getTextContent()); } } list.add(new Employee( Long.parseLong(elements.get(0)), elements.get(1), elements.get(2), elements.get(3), Integer.parseInt(elements.get(4)))); elements.clear(); } } return list; } private static List<Employee> jsonToList(String json, String newFileName) { List<Employee> list = new ArrayList<>(); GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); try { Object obj = new JsonParser().parse(json); JsonArray array = (JsonArray) obj; for (Object a : array) { list.add(gson.fromJson(a.toString(), Employee.class)); } } catch (Exception e) { e.printStackTrace(); } return list; } private static String readString(String newFileName) { StringBuilder sb = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader(newFileName))) { String s; while ((s = br.readLine()) != null) { sb.append(s).append("\n"); } } catch (IOException ex) { System.out.println(ex.getMessage()); } return sb.toString(); } }