出于某种原因,尽管配置了 FasterXML Jackson CSV 映射器来创建基于 POJO 的模式,但它坚持认为没有提供合适的配置。我得到以下异常:
com.fasterxml.jackson.databind.JsonMappingException: No value type configured for ObjectReader
com.fasterxml.jackson.databind.ObjectReader._findRootDeserializer(ObjectReader.java:1371)
com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1265)
com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:897)
aol.model.core.services.admin.CSVParserService.parseCSVFileStreamAsClass(CSVParserService.java:42)
aol.rest.controller.AdminController.importCsvData(AdminController.java:30)
aol.rest.controller.AdminController$$FastClassBySpringCGLIB$$b9304c43.invoke(<generated>)
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
...
我的 POJO 很简单
@JsonPropertyOrder({"firstName", "lastName", "age"})
public class Person {
String firstName;
String lastName;
Integer age;
public Person() {} //no other use than to avoid no-suitable-construction found issue
//getters and setters omitted for brevity
}
我的解析代码是
public MappingIterator<Person> parseCSVFileStreamAsClass(MultipartFile file) throws IOException {
StringBuilder lines = new StringBuilder();
String lineSeparator = System.getProperty("line.separator");
try(BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
for (String r = reader.readLine(); r != null; r = reader.readLine()) {
lines.append(r).append(lineSeparator);
}
}
CsvMapper mapper = new CsvMapper();
CsvSchema schema = mapper
.schemaFor(Person.class)
.withHeader()
.withLineSeparator(lineSeparator);
MappingIterator<Person> out = mapper.reader(schema).readValue(lines.toString());
return out;
}
我以这种方式处理 MultipartFile 而不是直接读取流的原因是消除了文件和映射器之间不匹配行分隔符的问题(我在 Windows 上工作 [不要对我投反对票 :(],而映射器的默认行分隔符仅\n
.
数据文件是这个
名字,姓氏,年龄
"保罗","史密斯","22"
《简》、《粗鲁》、《98》
我尝试添加和删除引号(默认字符串分隔符)。我尝试不使用年龄数字引号,然后出于绝望添加了它们。没有欢乐!
我查看了其他 SO 问题以及博客文章的文档。没运气。