杰克逊从CSV反序列化到枚举

时间:2018-05-04 21:26:13

标签: java json serialization jackson

我试图使用Jackson的数据格式库将足球结果csv反序列化为枚举。这是csv文件(第六列是我感兴趣的那个):

Egypt,Uruguay,GROUP,2,0,HOME

这是我的枚举类:

@JsonIgnoreProperties(ignoreUnknown = true)
public enum MatchOutcome {

    HOME(3, 0),
    DRAW(1, 1),
    AWAY(0, 3),
    HOME_ET(1, 1),
    AWAY_ET(1, 1),
    HOME_PENS(1, 1),
    AWAY_PENS(1, 1);

    private final Integer homePoints;
    private final Integer awayPoints;

    MatchOutcome(Integer homePoints, Integer awayPoints) {
        this.homePoints = homePoints;
        this.awayPoints = awayPoints;
    }

    public Integer homePoints() {
        return this.homePoints;
    }

    public Integer awayPoints() {
        return this.awayPoints;
    }
}

这是主要方法:

public static void main(String[] args) throws Exception {

    CsvSchema csvSchema = CsvSchema.builder()
            .addColumn("HOME")
            .addColumn("AWAY")
            .addColumn("STAGE")
            .addColumn("HOME_FULL_TIME")
            .addColumn("AWAY_FULL_TIME")
            .addColumn("MATCH_OUTCOME")
            .build();

    CsvMapper csvMapper = new CsvMapper();

    File csvFile = new File("src/Resources/fixtureResult.csv");

    MappingIterator<MatchOutcome> matchOutcomeIterator = csvMapper.readerFor(MatchOutcome.class).with(csvSchema)
            .readValues(csvFile);


    while (matchOutcomeIterator.hasNextValue()) {

        MatchOutcome matchOutcome = matchOutcomeIterator.nextValue();
        System.out.println(matchOutcomeIterator.toString());

    }

}

我收到以下错误:

Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.football.Calculator.MatchOutcome` out of START_OBJECT token

我的注释错了吗?或者我的枚举上需要一个toString方法吗?

1 个答案:

答案 0 :(得分:0)

我创建了一个包装类并最终映射到它,

@JsonIgnoreProperties(ignoreUnknown = true)
public class MatchOutcomeWrapper {

public MatchOutcome matchOutcome;

public MatchOutcomeWrapper(@JsonProperty("MATCH_OUTCOME") MatchOutcome matchOutcome) {
    this.matchOutcome = matchOutcome;
}

public MatchOutcome getMatchOutcome() {
    return matchOutcome;
}

public String toString() {

    return new ToStringBuilder(this, ToStringStyle.JSON_STYLE)
            .append("matchOutcome", matchOutcome)
            .toString();
}
}
相关问题