I have created an CSV exporter where I am converting String in JSON format into the Collection of objects and then into the List of strings.
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();
Now, I would like to do the adding of a new string into the List dynamically and replace this row: strings.add(obj.getName() + ";" + obj.getNumber() +"\n");
It should be more robust. Is somehow possible call all getters if I dont know exact names of properties?
Or is better solution how to convert String in JSON format into the List of strings?
Any advice would be appreciated!