Java是一種流行的編程語言,它被廣泛應用于大型企業級應用程序的開發中。在Java中,處理JSON(JavaScript Object Notation)和CSV(Comma-Separated Values)文件是很常見的需求。示例代碼如下:
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; public class JsonCsvExample { public static void main(String[] args) throws JsonProcessingException, IOException { // 創建一個對象列表 ListpersonList = new ArrayList<>(); personList.add(new Person("張三", 28)); personList.add(new Person("李四", 30)); personList.add(new Person("王五", 32)); // 將對象列表轉換為JSON字符串 ObjectMapper objectMapper = new ObjectMapper(); String jsonContent = objectMapper.writeValueAsString(personList); System.out.println("JSON字符串:" + jsonContent); // 將JSON字符串轉換為對象列表 List personListFromJson = objectMapper.readValue(jsonContent, objectMapper.getTypeFactory().constructCollectionType(List.class, Person.class)); System.out.println("對象列表:" + personListFromJson); // 將對象列表寫入CSV文件 CsvMapper csvMapper = new CsvMapper(); CsvSchema csvSchema = csvMapper.schemaFor(Person.class).withHeader(); FileWriter fileWriter = new FileWriter(new File("persons.csv")); csvMapper.writer(csvSchema).writeValues(fileWriter).writeAll(personList); fileWriter.flush(); fileWriter.close(); // 從CSV文件中讀取對象列表 List personListFromCsv = csvMapper.readerFor(Person.class).with(csvSchema).readValues(new File("persons.csv")).readAll(); System.out.println("對象列表:" + personListFromCsv); } } class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
上面的代碼演示了如何使用Java將對象列表轉換為JSON字符串,并從JSON字符串中讀取對象列表。還演示了如何將對象列表寫入CSV文件,并從CSV文件中讀取對象列表。