Java 将JSON格式的字符串转换为CSV/字符串列表

Java 将JSON格式的字符串转换为CSV/字符串列表,java,json,jsf,csv,jsf-2,Java,Json,Jsf,Csv,Jsf 2,我创建了一个CSV导出器,将JSON格式的字符串转换为对象集合,然后再转换为字符串列表 Gson gson = new Gson(); Type collectionType = new TypeToken<Collection<itemModel>>(){}.getType(); Collection<itemModel> objects = gson.fromJson(jsonString, collectionType); // jsonStrin

我创建了一个CSV导出器,将JSON格式的字符串转换为对象集合,然后再转换为字符串列表

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();
Gson-Gson=new-Gson();
Type collectionType=new-TypeToken(){}.getType();
Collection objects=gson.fromJson(jsonString,collectionType);
//jsonString=“[{”name:“A”,“number”:25},{”name:“B”,“number”:26}”
字符串filename=“export.csv”;
FacesContext fc=FacesContext.getCurrentInstance();
ExternalContext ec=fc.getExternalContext();
ec.responseReset();
ec.setResponseContentType(“文本/逗号分隔值”);
ec.setResponseHeader(“内容处置”、“附件;文件名=\”“+文件名+”\”);
OutputStream output=ec.getResponseOutputStream();
列表字符串=新的ArrayList();
对于(itemModel obj:对象){
strings.add(obj.getName()+“;”+obj.getNumber()+“\n”);
}
用于(字符串s:字符串){
output.write(s.getBytes());
}
fc.responseComplete();
现在,我想动态地将一个新字符串添加到列表中并替换此行:
strings.add(obj.getName()+”;“+obj.getNumber()+”\n”)它应该更健壮。如果我不知道属性的确切名称,是否可以调用所有getter

或者更好的解决方案是如何将JSON格式的字符串转换为字符串列表


任何建议都将不胜感激

您需要重写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();
}
//最后一句话

 List<itemModel> itemModels = gson.fromJson(jsonString, collectionType);
         for (itemModel itemModel : itemModels) {
               output.write(itemModel.toString().getBytes());
        }
List itemModels=gson.fromJson(jsonString,collectionType);
对于(itemModel itemModel:itemModels){
output.write(itemModel.toString().getBytes());
}
如果您已经知道所有属性,那么实现ItemModel的toString()是很好的


如果您不知道所有属性,可以使用反射来获取它们。

尝试此链接。我希望这会对你有所帮助。谢谢你的建议,但我看不出有可能的解决办法。我需要动态调用对象类的所有getter。。或者找到另一个更好的解决方案。太棒了!它可能永远也想不到。谢谢你的推荐!我试图实现反射,但没有解决如何在(itemModel obj:objects){}
的循环
中调用找到的getter,但toString()对我来说已经足够了。