Home > Mobile >  How to return a csv in java using Gson?
How to return a csv in java using Gson?

Time:01-10

I need to create a function that will read a JsonArray(gson) and transform it into CSV.

I tried using openCSV, but I couldn't, OpenCSV already expects a list to create the csv and I couldn't convert the JsonArray to a list.

My Codes;

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();
}

The error :

<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>

thanks in advance

CodePudding user response:

Resolved.

The solution was as follows:

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  ;
    }

To access a value in GSON it is necessary to access the KEY, in this way you can obtain the value of the object,

  • Related