我有一个 Java 方法,它接收一个 CSV 值字符串和一个整数索引来引用 CSV 字符串中要解析的列。该方法返回与 CSV 字符串中的整数索引关联的值。
例如,如果我有一个带有标题的 CSV 字符串,第二行的值定义为:
String csvString = "Entry #,Date Created,Date Updated, IP Address
165,8/22/13 14:46,,11.222.33.444";
并且该方法接收到的整数索引是 1,我希望该方法返回字符串“165”
如果该方法接收到的整数索引是 2,我希望该方法返回字符串“8/22/13 14:46”
等...
我不想只用逗号分割 CSV 字符串,因为那样会变得丑陋,而且我确信有一个 CSV 解析器已经可以像这样进行一些解析。根据我的 Google 搜索,OpenCSV 或 Jackson CsvMapper 似乎可以做到这一点。
我一直在使用 com.fasterxml.jackson.dataformat.csv.CsvMapper 库来解析这个 CSV 字符串的相应列,这是我目前所拥有的:
int csvFieldIndex (this is the integer index passed into my method)
String csvString = "Entry #,Date Created,Date Updated, IP Address
165,8/22/13 14:46,,11.222.33.444";
CsvSchema csvSchema = CsvSchema.emptySchema().withHeader();
ObjectReader mapper = new CsvMapper().reader(Map.class).with(csvSchema);
MappingIterator<Map<String, Object>> iter = null;
iter = mapper.readValues(csvString);
while (iter.hasNext()) {
Map<String, Object> row = iter.next();
System.out.Println("row= " + row.toString());
}
但是这个迭代器给了我所有的 csv 值,这不是我想要的;我只想要与我的整数索引关联的一个值。
这是我运行这段代码时得到的输出:
row= {Entry #=165, Date Created=8/22/13 14:46, Date Updated=, IP Address=11.222.33.444}
有没有一种方法可以使用 Jackson CsvMapper 来做到这一点?
========更新:========
根据 keshlam 的反馈,我能够使用以下代码解析 CSV 中的列:
CsvSchema csvSchema = CsvSchema.emptySchema().withHeader();
ObjectReader mapper = new CsvMapper().reader(Map.class).with(csvSchema);
MappingIterator<Map<String, Object>> iter = null;
iter = mapper.readValues(csvString);
// iterate over whole csv and store in a map
Map<String, Object> row = null;
while (iter.hasNext()) {
row = iter.next();
}
// now put the set of field names (keys) from this map into an array
String[] csvKeysArray = row.keySet().toArray(new String[0]);
int j = 0;
// loop over this array of keys and compare with csvFieldIndex
for (int i = 0; i < csvKeysArray.length; i++) {
// increment j by 1 since array index starts at 0 but input index starts at 1
j = i + 1;
if (j == csvFieldIndex) {
csvValue = row.get(csvKeysArray[i]).toString();
}
}
return csvValue;
最佳答案
如果我按照您的要求进行操作,并且正确理解了您的代码(我从未使用过 CsvMapper),请将最终循环更改为
while (iter.hasNext()) {
Map<String, Object> row = iter.next();
System.out.Println("Entry #= " + row.get("Entry #");
}
如果您想按数字而不是按名称访问列(为什么?),请设置从数字到列名的映射,并使用它来检索传递给 get() 操作的键。
关于java - 如何使用 jackson CsvMapper 或其他 csv 解析器解析 CSV 字符串中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21007485/