jackson-dataformat-csv:不带POJO的映射数字值 [英] jackson-dataformat-csv: Mapping number value without POJO

查看:262
本文介绍了jackson-dataformat-csv:不带POJO的映射数字值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jackson-dataformat-csv解析CSV文件,并且想将数字列映射到Number java类型.

I'm trying to parse a CSV file using jackson-dataformat-csv and I want to map the numeric column to the Number java type.

CsvSchema schema = CsvSchema.builder().setUseHeader(true)
    .addColumn("firstName", CsvSchema.ColumnType.STRING)
    .addColumn("lastName", CsvSchema.ColumnType.STRING)
    .addColumn("age", CsvSchema.ColumnType.NUMBER)
    .build();

CsvMapper csvMapper = new CsvMapper();  

MappingIterator<Map<String, Object>> mappingIterator = csvMapper
        .readerFor(Map.class)
        .with(schema)
        .readValues(is);        

while (mappingIterator.hasNext()) {
    Map<String, Object> entryMap = mappingIterator.next();
    Number age = (Number) entryMap.get("age");
}       

我期望entryMap.get("age")应该是Number,但是我却得到了String.

I'm expecting entryMap.get("age") should be a Number, but I get String instead.

我的CSV文件:

firstName,lastName,age
John,Doe,21
Error,Name,-10

我知道CsvSchema在POJO上可以很好地工作,但是我需要处理任意的CSV模式,所以我不能为每种情况创建一个新的Java类.

I know that CsvSchema works fine with POJOs, but I need to process arbitrary CSV schemas, so I can't create a new java class for every case.

是否可以将CSV解析为键入的MapArray?

Any way to parse CSV into a typed Map or Array?

推荐答案

您可以使用

You can use univocity-parsers for this sort of thing. It's faster and way more flexible:

var settings = new CsvParserSettings(); //configure the parser if needed
var parser = new CsvParser(settings);

for (Record record : parser.iterateRecords(is)) {
    Short age = record.getShort("age");
}

要获取类型化的映射,请告诉解析器您使用的列的类型是什么:

To get a typed map, tell the parser what is the type of the columns you are working with:

parser.getRecordMetadata().setTypeOfColumns(Short.class, "age" /*, and other column names*/);

//to get 0 instead of nulls when the field is empty in the file:
parser.getRecordMetadata().setDefaultValueOfColumns("0", "age", /*, and other column names*/);

// then parse
for (Record record : parser.iterateRecords(is)) {
    Map<String,Object> map = record.toFieldMap();
}

希望这会有所帮助

免责声明:我是这个图书馆的作者.它是开源且免费的(Apache 2.0许可证)

Disclaimer: I'm the author of this library. It's open source and free (Apache 2.0 license)

这篇关于jackson-dataformat-csv:不带POJO的映射数字值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆