我需要将http响应转换为Model,并且响应为纯csv格式:
try { StringReader stringReader = new StringReader(string); CSVReader csvReader = new CSVReaderBuilder(stringReader).build(); CsvToBean<SampleModel> csvToBean = new CsvToBeanBuilder<SampleModel>(csvReader) .withType(SampleModel.class) .withIgnoreLeadingWhiteSpace(true) .build(); arrayList =(ArrayList<SampleModel>)csvToBean.parse(); } catch (Exception e) { System.out.println(e.getMessage()); }
这让我感到异常:
捕获CSV标头时出错!
该字符串如下所示:
Name, Date Alex, 2012-10-30 Borhan, 2012-11-05
我一直在这里关注以下工作:https : //sourceforge.net/p/opencsv/bugs/196/#ee18
如果您有一个或多个带有参数的构造函数,请在bean类中显式创建一个无参数的构造函数。如果您没有一个或多个带参数的构造函数,则无需显式创建无参数构造函数。
SampleModel.java:
import com.opencsv.bean.CsvBindByName; public class SampleModel { @CsvBindByName(column = "Name") private String name; @CsvBindByName(column = "Date") private String date; public SampleModel() { // Empty } public SampleModel(String name, String date) { this.name = name; this.date = date; } public void setName(String name) { this.name = name; } public void setDate(String date) { this.date = date; } @Override public String toString() { return "{" + name + ", " + date + "}"; } }
如您所见,我有一个两个参数的构造函数,因此需要显式提供一个无参数的构造函数。如果删除no- arg构造函数并运行Main.java(如下所述),它将在运行时失败。
Main.java
但是,bean的以下定义不需要显式的无参数构造函数。您可以通过Main.java使用此定义再次运行来验证它。
import com.opencsv.bean.CsvBindByName; public class SampleModel { @CsvBindByName(column = "Name") private String name; @CsvBindByName(column = "Date") private String date; public void setName(String name) { this.name = name; } public void setDate(String date) { this.date = date; } @Override public String toString() { return "{" + name + ", " + date + "}"; } }
Main.java:
import java.io.StringReader; import java.util.List; import com.opencsv.CSVReader; import com.opencsv.CSVReaderBuilder; import com.opencsv.bean.CsvToBeanBuilder; public class Main { public static void main(String[] args) { String string = "Name, Date\n" + "Alex, 2012-10-30\n" + "Borhan, 2012-11-05"; try { StringReader stringReader = new StringReader(string); CSVReader csvReader = new CSVReaderBuilder(stringReader).build(); List<SampleModel> arrayList= new CsvToBeanBuilder<SampleModel>(csvReader) .withType(SampleModel.class) .withIgnoreLeadingWhiteSpace(true) .withSkipLines(1)// Skip the header line .build() .parse(); System.out.println(arrayList); } catch (Exception e) { e.printStackTrace(); } } }
输出:
[{Alex, 2012-10-30}, {Borhan, 2012-11-05}]
一种解决方法是从您从CSV读取的每个记录中创建bean的实例,并将该实例添加到List,如下所示:
List
List<SampleModel> arrayList = new ArrayList<>(); String[] nextRecord; CSVReader csvReader = new CSVReaderBuilder(stringReader) .withSkipLines(1)// Skip the header line .build(); while ((nextRecord = csvReader.readNext()) != null) { arrayList.add(new SampleModel(nextRecord[0], nextRecord[1])); }