---
# System prepended metadata

title: Java - 讀取csv檔並轉換成JSON格式
tags: [Advanced Java, Java]

---

# Java - 讀取csv檔並轉換成JSON格式

###### tags: `Java` `Advanced Java`

1. 增加dependency(pom.xml)
利用jackson-dataformat-csv套件
```
<dependency>
    	<groupId>com.fasterxml.jackson.dataformat</groupId>
    	<artifactId>jackson-dataformat-csv</artifactId>
    	<version>2.13.4</version>
</dependency>
```


2. 範例code(轉換成list以便於統計與處理)
```
	public static List<Map<String, String>> csvToJsonString(File file) throws Exception {
	
		List<Map<String, String>> result = new ArrayList<>();
		CsvMapper csvMapper = new CsvMapper();
		CsvSchema csvSchema = csvMapper
				.schemaFor(Map.class)
				.withHeader();
    
		MappingIterator<Map<String, String>> objectMappingIterator =
				csvMapper.readerFor(Map.class)
				.with(csvSchema)
				.readValues(file);
		while (objectMappingIterator.hasNext()) {
			result.add(objectMappingIterator.next());
		}
		return result;
	}
```

