如何在java中使用Gson返回csv?

zfycwa2u  于 2023-01-10  发布在  Java
关注(0)|答案(1)|浏览(122)

我需要创建一个函数来读取JsonArray(gson)并将其转换为CSV。
我尝试使用openCSV,但我不能,OpenCSV已经需要一个列表来创建csv,我不能将JsonArray转换为列表。
我的代码;

public Report buildCsv2(@NonNull Report.Type type,
                       @NonNull String ev_json_in,
                       @NonNull String titulo) throws IOException 
{;
    StringBuffer dados = repository.getJson(ev_json_in);
    var data = dados.toString();

    Gson gson = new Gson();
    JsonObject object = gson.newBuilder().create().fromJson(data, 
JsonObject.class);
    JsonArray array = object.getAsJsonArray(titulo);

    return Report.builder()
            .body(CsvHelper.createCsvFile(array))
            .type(type.getMediaType())
            .filename(titulo)
            .build();
}

   public static Object createCsvFile(JsonArray array) {
    File file = new File("csv.csv");

    try {
        FileWriter outputfile = new FileWriter(file);
        CSVWriter writer = new CSVWriter(outputfile);
        List data = array.asList();

        writer.writeAll(data);
        writer.close();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    return file.getName();
}

错误:

<message>class com.google.gson.JsonObject cannot be cast to class [Ljava.lang.String; (com.google.gson.JsonObject is in unnamed module of loader 'app'; [Ljava.lang.String; is in module java.base of loader 'bootstrap')</message>

先谢了

zsohkypk

zsohkypk1#

解决了。
解决方案如下:

var header = array.get(0).getAsJsonObject().keySet();
    for (int j = 0; j < header.size(); j++) {
        for (Object cab : header) {
            rowhead.createCell(j).setCellValue(cab.toString());
            j++;
        }
    }

    int l = 1;
    for (int i = 1; i < array.size(); i++) {

        for (Object aray : array){
            HSSFRow row = sheet.createRow((short) l);
            JsonObject values = array.get(i).getAsJsonObject();
            Set<String> keys = values.keySet();
            int c = 0;
            for (String key: keys) {
                row.createCell(c).setCellValue(values.get(key).toString());
                c++;
            }
        }
        l++;
    }

要访问GSON中的值,必须访问KEY,通过这种方式可以获得对象的值。

相关问题