j**a实体类怎么转换成json。

时间:2016.01.08 发布人:menyi_liu

j**a实体类怎么转换成json。

已解决问题

谷歌menyi_liu用户在2016.01.08提交了关于“北岛j**a实体类怎么转换成json。”的提问,欢迎大家涌跃发表自己的观点。目前共有1个回答,最后更新于2024-11-02T18:53:15。希望大家能够帮助她。

详细问题描述及疑问:期待您的答案,希望你能感受到,我最真诚的谢意 !

希望以下的回答,能够帮助你。

第1个回答

用户名:蕾啦409795074  

实例代码:
publicclassJSO**ti来自l{
/**
*将json转化为实体POJO
*@paramjsonStr
*@paramo何侵养都面行煤重段察等bj
*@return
*/
publicstatic<T>ObjectJSONToObj(StringjsonStr,Class<T>obj){
Tt=**ll;
try{
ObjectMapperobjectMapper=newObjectMapper();
t=objectMap助济水罪责耐负雷朝刑怀per.readValue(jsonStr,
obj);
}catch(Exceptione){
e.printStackTrace();
}
returnt;
}
/**
*将实体POJO转化为JSON
*@paramobj
*@return
*@throwsJSONException
*@throwsIOException
*/
publicstatic<T>J问答SONObjectobjectToJson(Tobj)throwsJSONException,IOExcep兴然饭到息tion{
ObjectMappermapper=newObjectMapper();
//ConvertobjecttoJSONstring
StringjsonStr="";
try{
jsonStr=mapp却值经至等映er.writeValueAsString(obj);
}catch(IOExceptione){
th办七路农rowe;
}
returnnew**才听杆半志权垂JSONObject(jsonStr);
}
publicstaticvoidmain(String[]args)throwsJSONException,IOException{
JSONObjectobj=**ll;
o养先接第乐宁逐无而活深bj=newJSONObject();
obj.put("name","213");
obj.put("ag率植士们号使让e",27);
JSONArrayarray=newJSONArray();
array.put(o先bj);
obj=newJSONObject();
obj.put("name","214");
obj.put("age",28);
array.put(obj);
Studentstu=(洲笔铁足美执Student)JSONToObj(obj.toSt政宁经适临继练ring(),Student.class);
JSONObjectobjList=newJSONObject();
objList.put("student",array);
System.out.println("objList:"+objList);
StudentListstuList=(StudentList)JSONToObj板至着神散值执迫补鲜(objList.toString(),StudentList.class);
System.o此但增混呢呢普已么只ut.printl杆之立助空类皇妒架否n("student:"+江再刑stu);
System.o级袁才月ut.println("stuList:"+stuList);
System.out.println("####################################器#");
JSONObjectgetObj=objectToJson(stu);
System.out.println(getObj);
}
}