I'm trying to use Jackson to convert some JSON into an instance of a class that contains some simple Strings and another class, which I'm using @JsonCreator for. It seems that Jackson isn't able to create the instance of the other class.
The problem is that when I run this code as part of a test:
ObjectMapper mapper = new ObjectMapper();
Player player = mapper.readValue(json.toString(), Player.class);
I get 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"])
The JSON I'm trying to parse in my simple test looks like this:
{
"name": "joe",
"characterClass": "warrior",
"difficulty": "easy",
"timesDied": 2
}
I have a class 'Player' 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 another class 'Character' that 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 sets of data like this there would be better ways to structure the whole thing, but I think this works for the purposes of an example. The real code I have is more complex but I wanted to make simple example.
I think I've messed up the Jackson annotations, but I'm not sure what I've done wrong.