2014-04-15 156 views
0

我创建了一个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格式的字符串转换为字符串列表?

任何意见将不胜感激!

+0

试试这个链接http://stackoverflow.com/questions/8724866/how-to-convert-data-base-records-into-csv-file-in-android。我希望这能帮到您。 – malavika

+0

感谢您的建议,但我没有看到有可能的解决方案。我需要动态调用对象类的所有getter或找到另一个更好的解决方案。 – PrincAm

回答

0

你需要重写itemModel类的toString()方法,并建立根据CSV您的字符串foramt

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

//最后wrtie

List<itemModel> itemModels = gson.fromJson(jsonString, collectionType); 
     for (itemModel itemModel : itemModels) { 
       output.write(itemModel.toString().getBytes()); 
     } 
+0

绝对精彩!它可能永远不会知道这一点。 – PrincAm

0

实施的toString()ItemModel的是好的,如果你已经知道所有的属性。

如果你已经不知道它们,你可以使用Reflection来获得所有的属性。

+0

感谢您的推荐!我试图实现反射,但我没有解决如何在循环内调用找到的getter(for itemModel obj:objects){}'但仍然toString()对我来说已经足够了。 – PrincAm