java - How to create an object factory method for gson method? -
i generating student object json object problem when create object want update "studentclass" field. update setstudentclass() method think gson doesn't use setter fields. how can create factory method fromjson() method?
student student = gson.fromjson(studentjson.tostring(), student.class); student.updateclassinfo(); public class student{ private string name; private string studentclass; //getters , setters public void updateclassinfo(){ if(studentclass.equals("1")) studentclass = "starter"; else if ..... } }
this requirement can fulfilled using custom deserializer. sample code below:-
main method:-
public static void main(string[] args) { string jsonstring = "{\"name\":\"john\",\"studentclass\":\"1\"}"; //string jsonstring = "{\"name\":\"john\"}"; gson gson = new gsonbuilder() .registertypeadapter(student.class, new studentmodeldeserializer()) .create(); student student = gson.fromjson(jsonstring, student.class); system.out.println(student.tostring()); }
deserializer:-
public class studentmodeldeserializer implements jsondeserializer<student> { @override public student deserialize(jsonelement paramjsonelement, type paramtype, jsondeserializationcontext paramjsondeserializationcontext) throws jsonparseexception { string studentclass = null; if (paramjsonelement.getasjsonobject().get("studentclass") != null) { studentclass = paramjsonelement.getasjsonobject().get("studentclass").getasstring(); } student student = new gson().fromjson(paramjsonelement.getasjsonobject(), student.class); if (studentclass != null) { if (studentclass.equals("1")) { student.setstudentclass("starter"); } } return student; } }
output:-
student [name=john, studentclass=starter]
output if student class not present:-
student [name=john, studentclass=null]
Comments
Post a Comment