英文:
Jackson CSV mapper doesn't insert CSV file content correctly (header doesn't match values)?
问题
我有一个名为`pets.csv`的CSV文件:
编号,名称,类型
1,杰克,狗
2,拉塞尔,猫
3,格瑞特,老鼠
我为每个`宠物`创建了一个自定义类:
@JsonPropertyOrder({ "NUMBER", "NAME", "TYPE" })
public class Pet {
public String number;
public String name;
public String type;
}
然后在`main`类中,我希望从`pets.csv`中提取数据到`List<Pet>`中:
public static void main(String[] args) throws IOException {
List<Pet> pets = readFile(Path.of("pets.csv"));
pets.forEach(pet -> System.out.println(pet.name));
}
public static List<Pet> readFile(Path csvFile) throws IOException {
try(MappingIterator<Pet> petIter = new CsvMapper()
.readerWithTypedSchemaFor(Pet.class).readValues(csvFile.toFile())) {
return petIter.readAll();
}
}
然而,我得到的输出不是:
名称
杰克
拉塞尔
格瑞特
而是:
编号
1
2
3
我做错了什么? :)
英文:
I have a CSV file pets.csv
:
NUMBER,NAME,TYPE
1,Jack,Dog
2,Russel,Cat
3,Great,Mouse
I have a custom class for each of the pets
:
@JsonPropertyOrder({ "NUMBER", "NAME", "TYPE" })
public class Pet {
public String number;
public String name;
public String type;
}
Then inside main
class I wish to fetch data from pets.csv
into List<Pet>
:
public static void main(String[] args) throws IOException {
List<Pet> pets = readFile(Path.of("pets.csv"));
pets.forEach(pet -> System.out.println(pet.name));
}
public static List<Pet> readFile(Path csvFile) throws IOException {
try(MappingIterator<Pet> petIter = new CsvMapper()
.readerWithTypedSchemaFor(Pet.class).readValues(csvFile.toFile())) {
return petIter.readAll();
}
}
However instead of having an output of:
NAME
Jack
Russel
Great
I got:
NUMBER
1
2
3
What am I doing wrong?
答案1
得分: 1
重新创建并且如果符合以下条件则运行完美:
@JsonPropertyOrder({ "number", "name", "type" })
public class Pet {
public String number;
public String name;
public String type;
}
所以,请将它们改为小写。希望这有所帮助
英文:
Recreated and works perfectly if:
@JsonPropertyOrder({ "number", "name", "type" })
public class Pet {
public String number;
public String name;
public String type;
}
So, lowercase them. Hope this helps
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论