Unrecognized property with Jackson @JsonCreator
I am trying to use Jackson to convert some JSON to an instance of a class that contains some simple strings and another class that I am using for @JsonCreator. It seems that Jackson cannot instantiate another class.
The problem is when I run this code as part of a test:
ObjectMapper mapper = new ObjectMapper();
Player player = mapper.readValue(json.toString(), Player.class);
I am getting the following exception:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "characterClass" (class xxx.xxx.Player), not marked as ignorable (2 known properties: "name", "character"])
JSON I'm trying to parse my simple test, looks like this:
{
"name": "joe",
"characterClass": "warrior",
"difficulty": "easy",
"timesDied": 2
}
I have a 'Player' class that looks a bit like this
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
}
And one more class "Symbol", which looks like this:
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
}
For small datasets like this, there would be better ways to structure the whole thing, but I think it works for example purposes. My real code is more complicated, but I wanted to make a simple example.
I think I messed up Jackson's annotations, but I'm not sure what I did wrong.
source to share
You need to point the creator to Player
that matches your JSON input. For example:
@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;
}
Note that you can structure your enums, for example and Jackson will do the string to enum conversion for you.
source to share