java - How to ignore enum fields in Jackson JSON-to-Object mapping? -
i have json object like:
{"name":"john", "grade":"a"}
or
{"name":"mike", "grade":"b"}
or
{"name":"simon", "grade":"c"}
etc
i trying map above json to:
@jsonignoreproperties(ignoreunknown = true) public class employee{ @jsonignoreproperties(ignoreunknown = true) public enum grade{ a, b, c } grade grade; string name; public grade getgrade() { return grade; } public void setgrade(grade grade) { this.grade = grade; } public string getname() { return name; } public void setname(string name) { this.name = name; } }
the above mapping works fine in future there more "grade" types let d,e etc breaks existing mapping , throws following exception
05-08 09:56:28.130: w/system.err(21309): org.codehaus.jackson.map.jsonmappingexception: can not construct instance of employee string value 'd': value not 1 of declared enum instance names
is there way ignore unknown fields in enum types?
thanks
i think should define external deserializer grade
enum.
i added additional field enum - unknown:
enum grade { a, b, c, unknown; public static grade fromstring(string value) { (grade grade : values()) { if (grade.name().equalsignorecase(value)) { return grade; } } return unknown; } } class employee { @jsondeserialize(using = gradedeserializer.class) private grade grade; private string name; public grade getgrade() { return grade; } public void setgrade(grade grade) { this.grade = grade; } public string getname() { return name; } public void setname(string name) { this.name = name; } @override public string tostring() { return "employee [grade=" + grade + ", name=" + name + "]"; } }
now, parser that:
class gradedeserializer extends jsondeserializer<grade> { @override public grade deserialize(jsonparser parser, deserializationcontext context) throws ioexception, jsonprocessingexception { return grade.fromstring(parser.getvalueasstring()); } }
example usage:
public class jacksonprogram { public static void main(string[] args) throws exception { objectmapper objectmapper = new objectmapper(); jsonfactory jsonfactory = new jsonfactory(); jsonparser parser = jsonfactory .createjsonparser("{\"name\":\"john\", \"grade\":\"d\"}"); employee employee = objectmapper.readvalue(parser, employee.class); system.out.println(employee); } }
output:
employee [grade=unknown, name=john]
if don't want add additional field, return null
example.
Comments
Post a Comment