[英]Convert String in JSON format into CSV / List of Strings
我创建了一个CSV导出器,将JSON格式的String转换为Object的集合,然后转换为String的列表。
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");
它应该更健壮。 如果我不知道属性的确切名称,是否可以以某种方式调用所有的获取方法?
还是更好的解决方案,如何将JSON格式的String转换为字符串列表?
任何意见,将不胜感激!
您需要在itemModel类中重写toString()方法,并根据CSV格式构建字符串
@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());
}
如果您已经知道所有属性,则实现ItemModel的toString()很好。
如果您尚不了解,可以使用Reflection获取所有属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.