【Java】jsonからcsvにする

久しぶりにjavajsoncsvを扱うことがあったのでメモ
ライブラリはjacksonを使います

サンプルのjson

[
    {
        "id": 1,
        "name": "xxxx",
        "stgflag": true,
        "info": [
            {
                "info_id": "info_xxxx01",
                "info_text": "textxxxx01"
            },
            {
                "info_id": "info_xxxx02",
                "info_text": "textxxxx02"
            }
        ]
    },
    {
        "id": 2,
        "name": "yyyy",
        "stgflag": false,
        "info": [
            {
                "info_id": "info_yyyy02",
                "info_text": "textyyyy01"
            },
            {
                "info_id": "info_yyyy02",
                "info_text": "textyyyy02"
            }
        ]
    }
]

jsonからObjectへ変換

準備

getter,setterは省略

public class Sample {
    private int id;
    private String name;
    private boolean stgflag;
    private List<Info> info;
}
public class Info {
    private String info_id;
    private String info_text;
}

実行

private void sample() throws FileNotFoundException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    try (FileInputStream br = new FileInputStream("sample.json")) {
        List<Sample> sampleList = mapper.readValue(br, new TypeReference<List<Sample>>() {});
        sampleList.stream().forEach(a -> {
            System.out.println(a.getId() + " " + a.getName());
            a.getInfo().stream().forEach(b -> System.out.println(b.getInfo_id() + " " + b.getInfo_text()));
        });
    }
}

結果

1 xxxx
info_xxxx01 textxxxx01
info_xxxx02 textxxxx02
2 yyyy
info_yyyy02 textyyyy01
info_yyyy02 textyyyy02

ObjectからCSVへ変換

準備

getter,setterは省略

public class CsvSample {

    private int id;
    private String name;
    private boolean stgflag;
    private String info;
}

実行

private void sample() throws FileNotFoundException, IOException {

    ObjectMapper mapper = new ObjectMapper();
    try (FileInputStream br = new FileInputStream("sample.json")) {
        List<Sample> sampleList = mapper.readValue(br, new TypeReference<List<Sample>>() {});

        CsvMapper csvmapper = new CsvMapper();
        CsvSchema schema = csvmapper.schemaFor(CsvSample.class).withHeader();

        List<CsvSample> csvSampleList = new ArrayList<>();
        for (Sample sample : sampleList) {
            CsvSample row = new CsvSample();
            row.setId(sample.getId());
            row.setName(sample.getName());
            row.setStgflag(sample.isStgflag());
            row.setInfo(mapper.writeValueAsString(sample.getInfo()));
            csvSampleList.add(row);
        }
        System.out.println(csvmapper.writer(schema).writeValueAsString(csvSampleList));
    }
}

結果

id,info,name,stgflag
1,"[{""info_id"":""info_xxxx01"",""info_text"":""textxxxx01""},{""info_id"":""info_xxxx02"",""info_text"":""textxxxx02""}]",xxxx,true
2,"[{""info_id"":""info_yyyy02"",""info_text"":""textyyyy01""},{""info_id"":""info_yyyy02"",""info_text"":""textyyyy02""}]",yyyy,false