java - Validate model when it is created from json string in spring -
i preparing model json string using json jackson object mapper in spring.
my code
objectmapper mapper = new objectmapper(); string empvalue = mapper.writevalueasstring(employeemap); employees employee = mapper.readvalue(empvalue, employees.class);
before preparing object of employee want validate json because if mismatched data set through exception while preparing model.how can it?
you can valuable information out of exception out of jsonmappingexception class , sub classes (under com.fasterxml.jackson.databind.exc package) using getpath , getpathreference methods
here 2 examples:
public class objectmappertest { private objectmapper objectmapper; @before public void setup() { objectmapper = new objectmapper(); } @test public void testwrongdatatype() { string personstr = "{\"age\":\"100y\",\"firstname\":\"jackson\",\"lastname\":\"pollock\",\"gender\":\"m\"}"; try { objectmapper.readvalue(personstr, person.class); } catch (jsonmappingexception jme) { system.out.println(jme.getmessage()); if(jme instanceof invalidformatexception) { invalidformatexception ife = (invalidformatexception)jme; system.out.println("mapping failure on field:" + ife.getpathreference()); system.out.println("expected type: " + ife.gettargettype()); system.out.println("provided value: " + ife.getvalue()); } }catch (exception e){ system.out.println(e.getmessage()); } } @test public void testunrecognizedproperty() { string personstr = "{\"gae\":\"100\",\"firstname\":\"jackson\",\"lastname\":\"pollock\",\"gender\":\"m\"}"; try { objectmapper.readvalue(personstr, person.class); } catch (jsonmappingexception jme) { system.out.println(jme.getmessage()); if(jme instanceof propertybindingexception) { propertybindingexception pbe = (propertybindingexception) jme; system.out.println("mapping failure on field:" + pbe.getpathreference()); system.out.println("unexpected field: " + pbe.getpropertyname()); } }catch (exception e){ system.out.println(e.getmessage()); } } }
the output
testunrecognizedproperty: ======================== unrecognized field "gae" (class person), not marked ignorable (4 known properties: "lastname", "gender", "firstname", "age"]) @ [source: {"gae":"100","firstname":"jackson","lastname":"pollock","gender":"m"}; line: 1, column: 9] (through reference chain: person["gae"]) mapping failure on field:person["gae"] unexpected field: gae testwrongdatatype: ======================== can not construct instance of java.lang.integer string value '100y': not valid integer value @ [source: {"age":"100y","firstname":"jackson","lastname":"pollock","gender":"m"}; line: 1, column: 2] (through reference chain: person["age"]) mapping failure on field:person["age"] expected type: class java.lang.integer provided value: 100y
Comments
Post a Comment