JSONをCSVに変換する
ファイル不正時などはいったん考慮せず、ロジックだけおぼえがき。
jsonToCsv.java
/**
* JSONをCSVに変換する.
*
* @throws IOException
*/
public static void jsonToCsv() throws IOException {
String json = "[{\"head1\":\"a\",\"head2\":\"b\",\"head3\":\"c\",\"head4\":\"d\",\"head5\":\"e\"},{\"head1\":\"1\",\"head2\":\"2\",\"head3\":\"3\",\"head4\":\"4\",\"head5\":\"5\"},{\"head1\":\"q\",\"head2\":\"qq\",\"head3\":\"qqq\",\"head4\":\"qqqq\",\"head5\":\"qqqqq\"}]";
// 両サイドの[]を排除し、},{で区切る イメージは "head1":"1","head2":"2","head3":"3","head4":"4","head5":"5"
List<String> trimJson = Arrays.asList(json.split("\\[")[1].split("\\]")[0].split("\\},\\{"));
// 1レコード1mapに成形する
Function<String, Map<String, String>> toMap = str -> {
Map<String, String> map = new HashMap<>();
for (String s : str.split(",")) {
String[] keyValue = s.split(":");
map.put(keyValue[0].split("\"")[1], keyValue[1].split("\"")[1]);
}
return map;
};
List<Map<String, String>> recordList = trimJson.stream()
.map(String::trim)
.map(v -> v.startsWith("\\{") ? v.split("\\{")[1] : v)
.map(toMap)
.collect(Collectors.toList());
// csvファイルを作成、書き込む
File csv = new File("csvファイルパス");
csv.createNewFile();
FileWriter filewriter = new FileWriter(csv);
String header = String.join(",", recordList.get(0).keySet());
String bodies = recordList.stream()
.map(Map::values)
.map(v -> String.join(",", v))
.collect(Collectors.joining("\r\n"));
filewriter.write(header + "\r\n");
filewriter.write(bodies);
filewriter.close();
}