我需要创建一个函数来读取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>
先谢了
1条答案
按热度按时间zsohkypk1#
解决了。
解决方案如下:
要访问GSON中的值,必须访问KEY,通过这种方式可以获得对象的值。