杰克逊CSV映射器未正确插入CSV文件内容(标题与值不匹配)?

huangapple go评论64阅读模式
英文:

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({ &quot;NUMBER&quot;, &quot;NAME&quot;, &quot;TYPE&quot; })
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&lt;Pet&gt;:

public static void main(String[] args) throws IOException {
    List&lt;Pet&gt; pets = readFile(Path.of(&quot;pets.csv&quot;));
    pets.forEach(pet -&gt; System.out.println(pet.name));
}

public static List&lt;Pet&gt; readFile(Path csvFile) throws IOException {
    try(MappingIterator&lt;Pet&gt; 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? 杰克逊CSV映射器未正确插入CSV文件内容(标题与值不匹配)?

答案1

得分: 1

重新创建并且如果符合以下条件则运行完美:

@JsonPropertyOrder({ "number", "name", "type" })
public class Pet {

    public String number;
    public String name;
    public String type;
}

所以,请将它们改为小写。希望这有所帮助 杰克逊CSV映射器未正确插入CSV文件内容(标题与值不匹配)?

英文:

Recreated and works perfectly if:

@JsonPropertyOrder({ &quot;number&quot;, &quot;name&quot;, &quot;type&quot; })
public class Pet {

    public String number;
    public String name;
    public String type;
}

So, lowercase them. Hope this helps 杰克逊CSV映射器未正确插入CSV文件内容(标题与值不匹配)?

huangapple
  • 本文由 发表于 2023年3月9日 23:04:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686401.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定