0

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!

PrincAm
  • 317
  • 5
  • 17
  • Try this link http://stackoverflow.com/questions/8724866/how-to-convert-data-base-records-into-csv-file-in-android. I hope this will help you. – malavika Apr 15 '14 at 13:02
  • Thanks for a recommendation but I don't see there a possible solution. I need to call all getters of object class dynamically.. or find another better solution. – PrincAm Apr 15 '14 at 13:15

2 Answers2

0

You need to override toString() method in itemModel Class and build your string according to CSV foramt

@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append(name);
    builder.append(";");
    builder.append(number);
    builder.append("\n");
    return builder.toString();
}

// finally wrtie

 List<itemModel> itemModels = gson.fromJson(jsonString, collectionType);
         for (itemModel itemModel : itemModels) {
               output.write(itemModel.toString().getBytes());
        }
Asif Bhutto
  • 3,916
  • 1
  • 24
  • 21
0

Implementing toString() of ItemModel is good if you already know all the properties.

You can use Reflection to get all the properties if you already don't know them.

Amit P
  • 467
  • 6
  • 20
  • Thanks for your recommendation! I was trying to implement Reflection but I didn't resolve how to call found getters inside loop `for (itemModel obj : objects) { }` But still toString() is sufficient for me. – PrincAm Apr 16 '14 at 09:18