CSV-03- csv 讀寫框架支持數組、Map、Collection 等常見集合

集合類

有時候對象中會包含數組、Map、Collection 等常見集合。

爲了存儲的便利性,默認提供集合的相關支持。

特性和普通字段保持一致,如果指定註解轉換,則以註解爲準。

使用示例

  • UserCollection.java

用於演示集合的對象

public class UserCollection {

    private String[] arrays;

    private LinkedList<String> lists;

    private Map<String, String> maps;

    private Set<String> sets;

    //Getter/Setter/toString()
}

存儲

  • 待存儲對象的構建
/**
 * 構建基於集合的測試列表
 * @return 列表
 * @since 0.0.3
 */
private List<UserCollection> buildCollectionList() {
    UserCollection user = new UserCollection();
    String[] arrays = new String[]{"a", "b", "c"};
    LinkedList<String> lists = new LinkedList<>(Arrays.asList(arrays));
    Map<String, String> maps = new HashMap<>();
    maps.put("key", "value");
    maps.put("key2", "value2");
    Set<String> sets = new HashSet<>();
    sets.add("set1");
    sets.add("set2");

    user.setLists(lists);
    user.setArrays(arrays);
    user.setMaps(maps);
    user.setSets(sets);
    return Arrays.asList(user);
}
  • 執行存儲
public void collectionTest() {
    final String path = "src\\test\\resources\\collection.csv";
    CsvWriteBs.newInstance(path)
            .write(buildCollectionList());
}
  • 存儲效果
arrays,lists,maps,sets
a|b,a|b|c,key2=value2|key=value,set1|set2

讀取

  • 測試類
public void collectionTest() {
    final String path = "src\\test\\resources\\collection.csv";
    List<UserCollection> userList = CsvReadBs.newInstance(path)
            .read(UserCollection.class);
    System.out.println(userList);
}
  • 測試日誌
[UserCollection{arrays=[a, b], lists=[a, b, c], maps={key=value, key2=value2}, sets=[set2, set1]}]

注意

爲了保證 csv 以 , 分隔的統一性。

集合使用 | 進行分隔,其中 map 的 key/value 分隔,用到了 =

在使用時要注意,不要包含上述的符號,否則會出現解析錯亂。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章