簡體   English   中英

將JSON格式的字符串轉換為CSV /字符串列表

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM