java中实体类和JSON对象之间相互转化
在需要用到JSON对象封装数据的时候,往往会写很多代码,也有很多复制粘贴,为了用POJO的思想我们可以装JSON转化为实体对象进行操作
packagemyUtil;
importjava.io.IOException;
importmyProject.Student;
importmyProject.StudentList;
importorg.codehaus.jackson.map.ObjectMapper;
importorg.json.JSONArray;
importorg.json.JSONException;
importorg.json.JSONObject;
/**
*实体类和JSON对象之间相互转化(依赖包jackson-all-1.7.6.jar、jsoup-1.5.2.jar)
*@authorwck
*
*/
publicclassJSONUtil{
/**
*将json转化为实体POJO
*@paramjsonStr
*@paramobj
*@return
*/
publicstatic<T>ObjectJSONToObj(StringjsonStr,Class<T>obj){
Tt=null;
try{
ObjectMapperobjectMapper=newObjectMapper();
t=objectMapper.readValue(jsonStr,
obj);
}catch(Exceptione){
e.printStackTrace();
}
returnt;
}
/**
*将实体POJO转化为JSON
*@paramobj
*@return
*@throwsJSONException
*@throwsIOException
*/
publicstatic<T>JSONObjectobjectToJson(Tobj)throwsJSONException,IOException{
ObjectMappermapper=newObjectMapper();
//ConvertobjecttoJSONstring
StringjsonStr="";
try{
jsonStr=mapper.writeValueAsString(obj);
}catch(IOExceptione){
throwe;
}
returnnewJSONObject(jsonStr);
}
publicstaticvoidmain(String[]args)throwsJSONException,IOException{
JSONObjectobj=null;
obj=newJSONObject();
obj.put("name","213");
obj.put("age",27);
JSONArrayarray=newJSONArray();
array.put(obj);
obj=newJSONObject();
obj.put("name","214");
obj.put("age",28);
array.put(obj);
Studentstu=(Student)JSONToObj(obj.toString(),Student.class);
JSONObjectobjList=newJSONObject();
objList.put("student",array);
System.out.println("objList:"+objList);
StudentListstuList=(StudentList)JSONToObj(objList.toString(),StudentList.class);
System.out.println("student:"+stu);
System.out.println("stuList:"+stuList);
System.out.println("#####################################");
JSONObjectgetObj=objectToJson(stu);
System.out.println(getObj);
}
}
以上所述就是本文的全部内容了,希望大家能够喜欢。