我创建了一个CSV导出器,我将JSON格式的字符串转换为对象集合,然后转换为字符串列表。现在将JSON格式的字符串转换为CSV /字符串列表
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<itemModel>>(){}.getType();
Collection<itemModel> objects = gson.fromJson(jsonString, collectionType);
// jsonString = "[{"name":"A","number":25},{"name":"B","number":26}]"
String filename = "export.csv";
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset();
ec.setResponseContentType("text/comma-separated-values");
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
OutputStream output = ec.getResponseOutputStream();
List<String> strings = new ArrayList<String>();
for (itemModel obj : objects) {
strings.add(obj.getName() + ";" + obj.getNumber() +"\n");
}
for (String s : strings) {
output.write(s.getBytes());
}
fc.responseComplete();
,我愿做一个新的字符串添加到列表动态和替换该行:strings.add(obj.getName() + ";" + obj.getNumber() +"\n");
应该更加强劲。如果我不知道属性的确切名称,是否可以调用所有getter?
或者更好的解决方案如何将JSON格式的字符串转换为字符串列表?
任何意见将不胜感激!
试试这个链接http://stackoverflow.com/questions/8724866/how-to-convert-data-base-records-into-csv-file-in-android。我希望这能帮到您。 – malavika
感谢您的建议,但我没有看到有可能的解决方案。我需要动态调用对象类的所有getter或找到另一个更好的解决方案。 – PrincAm