[英]Reading a huge csv file and converting to JSON with Java 8
我正在嘗試讀取包含許多列的csv文件。 第一行始終是csv文件的標題。 我想將csv數據轉換為JSON。 我可以將其作為String讀取並轉換為JSON,但我無法為其分配標頭。
例如輸入csv看起來像:
first_name,last_name
A,A1
B,B1
C,C1
Stream<String> stream = Files.lines(Paths.get("sample.csv"))
List<String[]> readall = stream.map(l -> l.split(",")).collect(Collectors.toList());
要么
List<String> test1 = readall.stream().skip(0).map(row -> row[1]).collect(Collectors.toList());
使用com.fasterxml.jackson.databind.ObjectMapper的WriteValueAsString只創建沒有頭的JSON。
我希望輸出格式如
{
[{"first_name":"A","last_name":"A1"},{"first_name":"B"....
如何在Java中使用流來准備此JSON格式?
請幫忙。
我將分兩步解決這個問題:首先,閱讀標題,然后閱讀其余部分:
static String[] headers(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine().split(",");
}
}
現在,您可以使用上面的方法,如下所示:
String path = "sample.csv";
// Read headers
String[] headers = headers(path);
List<Map<String, String>> result = null;
// Read data
try (Stream<String> stream = Files.lines(Paths.get(path))) {
result = stream
.skip(1) // skip headers
.map(line -> line.split(","))
.map(data -> {
Map<String, String> map = new HashMap<>();
for (int i = 0; i < data.length; i++) {
map.put(headers[i], data[i]);
}
return map;
})
.collect(Collectors.toList());
}
您可以在第二個map
操作中更改for
循環:
try (Stream<String> stream = Files.lines(Paths.get(path))) {
result = stream
.skip(1) // skip headers
.map(line -> line.split(","))
.map(data -> IntStream.range(0, data.length)
.boxed()
.collect(Collectors.toMap(i -> headers[i], i -> data[i])))
.collect(Collectors.toList());
}
編輯:如果不是收集到列表,而是要對從每行讀取的地圖執行操作,可以按如下方式執行:
try (Stream<String> stream = Files.lines(Paths.get(path))) {
stream
.skip(1) // skip headers
.map(line -> line.split(","))
.map(data -> IntStream.range(0, data.length)
.boxed()
.collect(Collectors.toMap(i -> headers[i], i -> data[i])))
.forEach(System.out::println);
}
(這里的動作是打印每張地圖)。
本版本可以被改善,即,它箱流int
秒,然后unboxes每個int
再次使用它作為的索引headers
和data
陣列。 此外,通過將每個映射的創建提取到私有方法,可以提高可讀性。
注意:也許讀取文件兩次並不是性能最好的方法,但代碼簡單而富有表現力。 除此之外, null
處理,數據轉換(即數字或日期等)和邊界情況(即沒有標題,沒有數據行或數據數組的不同長度等)留給讀者練習;)
我想這就是你想要做的
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class App {
public static void main(String[] args) throws JsonProcessingException, IOException {
Stream<String> stream = Files.lines(Paths.get("src/main/resources/test1.csv"));
List<Map<String, Object>> readall = stream.map(l -> {
Map<String, Object> map = new HashMap<String, Object>();
String[] values = l.split(",");
map.put("name", values[0]);
map.put("age", values[1]);
return map;
}).collect(Collectors.toList());
ObjectMapper mapperObj = new ObjectMapper();
String jsonResp = mapperObj.writeValueAsString(readall);
System.out.println(jsonResp);
}
}
使用帶有標頭的Java -8 Streams,並使用jackson將其轉換為json。 使用了CSV
abc,20
bbc,30
非常簡單,不要將其轉換為字符串列表。 將其轉換為HashMaps列表,然后使用org.json庫將其轉換為json。 使用jackson將CSV轉換為Hashmap
讓輸入流為
InputStream stream = new FileInputStream(new File("filename.csv"));
示例:將CSV轉換為HashMap
public List<Map<String, Object>> read(InputStream stream) throws JsonProcessingException, IOException {
List<Map<String, Object>> response = new LinkedList<Map<String, Object>>();
CsvMapper mapper = new CsvMapper();
CsvSchema schema = CsvSchema.emptySchema().withHeader();
MappingIterator<Map<String, String>> iterator = mapper.reader(Map.class).with(schema).readValues(stream);
while (iterator.hasNext())
{
response.add(Collections.<String, Object>unmodifiableMap(iterator.next()));
}
return response;
}
將Map的List轉換為Json
JSONArray jsonArray = new JSONArray(response);
System.out.println(jsonArray.toString());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.