When you need to encapsulate data with a JSON object, you often write a lot of code, and there's a lot of copy and paste, so that we can convert JSON to an entity object using Pojo's ideas
Package myutil;
Import java.io.IOException;
Import myproject.student;
Import myproject.studentlist;
Import Org.codehaus.jackson.map.ObjectMapper;
Import Org.json.JSONArray;
Import org.json.JSONException;
Import Org.json.JSONObject; /** * Convert between entity class and JSON object (dependent package Jackson-all-1.7.6.jar, Jsoup-1.5.2.jar) * @author WCK */public class Jsonutil {/** * Converts JSON to entity Pojo * @param jsonstr * @param obj * @return */public static<t> Object jsontoobj (String JS
Onstr,class<t> obj) {t = null;
try {objectmapper objectmapper = new Objectmapper ();
t = Objectmapper.readvalue (jsonstr, obj);
catch (Exception e) {e.printstacktrace ();
} return t; /** * Converts entity Pojo to JSON * @param obj * @return * @throws jsonexception * @throws ioexception * * publi C static<t> jsonobject Objecttojson (T obj) throws Jsonexception, IOException {objectmapper mapper = new OBJECTM
Apper (); Convert objecT to JSON string string jsonstr = "";
try {jsonstr = mapper.writevalueasstring (obj);
catch (IOException e) {throw e;
Return to New Jsonobject (JSONSTR);
public static void Main (string[] args) throws Jsonexception, IOException {jsonobject obj = null;
obj = new Jsonobject ();
Obj.put ("name", "213");
Obj.put ("Age", 27);
Jsonarray array = new Jsonarray ();
Array.put (obj);
obj = new Jsonobject ();
Obj.put ("name", "214");
Obj.put ("Age", 28);
Array.put (obj);
Student stu = (Student) jsontoobj (obj.tostring (), student.class);
Jsonobject objlist = new Jsonobject ();
Objlist.put ("Student", array);
System.out.println ("objlist:" +objlist);
Studentlist stulist = (studentlist) jsontoobj (objlist.tostring (), studentlist.class);
System.out.println ("Student:" +stu);
System.out.println ("stulist:" +stulist);
System.out.println ("#####################################"); Jsonobject getobj = ObjecttojSon (Stu);
System.out.println (Getobj);
}
}
The above is the entire contents of this article, I hope you can enjoy.