代码之家  ›  专栏  ›  技术社区  ›  womplefrog

如何序列化/反序列化整数列表?有了这个库,Quirk能做到这一点吗?

  •  0
  • womplefrog  · 技术社区  · 4 年前

    哟。

    我正在尝试这个新的CSV库怪癖CSV。我已经将其用于基本对象,但我正在尝试找出如何序列化/反序列化整数列表。这可能与怪癖有关吗?

         public static void main(String[] args) throws IOException {
                CSVProcessor<Client> parser = new CSVProcessor<>(Client.class);
                String header = "ID,NAME,AGENTS\n";
                String data = "1,client,2|4|66";
                List<Client> list = parser.parse(new StringReader(header+data), CSVFormat.DEFAULT.withIgnoreHeaderCase());
                StringWriter sw = new StringWriter();
                parser.write(list,sw,CSVFormat.DEFAULT);
                System.out.println(sw);
            }
        
            @CSVReadComponent(type = CSVType.NAMED)
            @CSVWriteComponent(type = CSVType.NAMED)
            public static class Client{
        
                @CSVReadBinding(header = "id")
                @CSVWriteBinding(header = "id")
                private long id;
        
                @CSVReadBinding(header = "name")
                @CSVWriteBinding(header = "name")
                private String name;
                
        
                @CSVReadBinding(header = "agents")
                @CSVWriteBinding(header = "agents")
                private List<Integer> agentIds;
                // Getters & Setters
                
            }
    
    ,,,
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   Austin Poole    4 年前

    很高兴看到有人用这个。

    我是 Quirk-CSV .这个用例解决起来还不错。您可以使用这样的内联包装器:

     @CSVReadBinding(header = "agents", wrapper = AgentsReadWrapper.class)
     @CSVWriteBinding(header = "agents", wrapper = AgentsWriteWrapper.class)
     private List<Integer> agentIds;
    
    
    
    public static class AgentsReadWrapper implements ReadWrapper<List<Integer>> {
    
        @Override
        public List<Integer> apply(String str) {
            if(Objects.isNull(str) || str.trim().isEmpty()){
                return new ArrayList<>();
            }
            return Arrays.stream(str.split("\\|"))
                    .map(String::trim)
                    .map(Integer::valueOf)
                    .collect(Collectors.toList());
        }
    }
    
    public static class  AgentsWriteWrapper implements WriteWrapper<List<Integer>>{
    
        @Override
        public String apply(List<Integer> str) {
            StringJoiner sj = new StringJoiner("|");
            str.stream().map(String::valueOf).forEach(sj::add);
            return sj.toString();
        }
    }
    

    如果您有任何问题,也可以在存储库中发布问题。我会尽快给你答复。