杰克逊@JsonCreator无法识别的财产

时间:2015-07-09 18:11:30

标签: java json jackson

我试图使用Jackson将一些JSON转换为包含一些简单字符串和另一个类的类的实例,我使用@JsonCreator。杰克逊似乎无法创建另一个类的实例。

问题在于,当我将此代码作为测试的一部分运行时:

ObjectMapper mapper = new ObjectMapper();
Player player = mapper.readValue(json.toString(), Player.class);

我得到以下异常:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "characterClass" (class xxx.xxx.Player), not marked as ignorable (2 known properties: "name", "character"])

我试图在我的简单测试中解析的JSON看起来像这样:

{
    "name": "joe",
    "characterClass": "warrior",
    "difficulty": "easy",
    "timesDied": 2
}

我有一个班级'播放器'看起来有点像这样

public class Player {

    @JsonProperty("name")
    private String playerName;

    @JsonProperty // <-- This is probably wrong
    private Character character;

    // Some getters and setters for those two fields and more
}

另一个班级&#39;角色&#39;看起来像这样

public class Character{
    private PlayerClass playerClass;
    private Difficulty difficulty;
    private int timesDied;

    @JsonCreator
    public Character(@JsonProperty("characterClass") String playerClass,
                       @JsonProperty("difficulty") String diff,
                       @JsonProperty("timesDied") int died) {

        // Validation and conversion to enums

        this.playerClass = PlayerClass.WARRIOR;
        this.difficulty = Difficulty.EASY;
        this.timesDied = died;
    }

    // Again, lots of getters, setters, and other stuff
}

对于像这样的小数据集,可以有更好的方法来构建整个事物,但我认为这可以用于示例的目的。我的真实代码更复杂,但我想做一个简单的例子。

我认为我搞砸了杰克逊的注释,但我不确定我做错了什么。

1 个答案:

答案 0 :(得分:1)

您需要在Player上指定与您的JSON输入匹配的创建者。例如:

@JsonCreator
public static Player fromStringValues(@JsonProperty("name") String name,
                                      @JsonProperty("characterClass") String characterClass,
                                      @JsonProperty("difficulty") String difficulty,
                                      @JsonProperty("timesDied") Integer timesDied) {
    Player player = new Player();
    player.setPlayerName(name);
    player.setCharacter(new Character(characterClass, difficulty, timesDied));
    return player;
}

旁注,你可以构建你的枚举,如this,杰克逊将为你做一个从字符串到枚举的转换。