java - Unrecognised Property with Jackson @JsonCreator -


i'm trying use jackson convert json instance of class contains simple strings , class, i'm using @jsoncreator for. seems jackson isn't able create instance of other class.

the problem when run code part of test:

objectmapper mapper = new objectmapper(); player player = mapper.readvalue(json.tostring(), player.class); 

i following exception:

com.fasterxml.jackson.databind.exc.unrecognizedpropertyexception: unrecognized field "characterclass" (class xxx.xxx.player), not marked ignorable (2 known properties: "name", "character"]) 

the json i'm trying parse in simple test looks this:

{     "name": "joe",     "characterclass": "warrior",     "difficulty": "easy",     "timesdied": 2 } 

i have class 'player' looks bit this

public class player {      @jsonproperty("name")     private string playername;      @jsonproperty // <-- wrong     private character character;      // getters , setters 2 fields , more } 

and class 'character' looks 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 , conversion enums          this.playerclass = playerclass.warrior;         this.difficulty = difficulty.easy;         this.timesdied = died;     }      // again, lots of getters, setters, , other stuff } 

for small sets of data there better ways structure whole thing, think works purposes of example. real code have more complex wanted make simple example.

i think i've messed jackson annotations, i'm not sure i've done wrong.

you need specify creator on player matches json input. 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; } 

a side note, can structure enums this , jackson conversion string enum you.


Comments