String JSON 与实体类之间的相互转换
package com.bc.mcode.controller.help;
import java.io.IOException;
import com.bc.mcode.model.UserExpandVO;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONObject;
public class JsonConversion {
//VO转String JSON串
public String toJsonString(UserExpandVO userExpandVO) throws IOException {
/*ObjectMapper mapper = new ObjectMapper();
// User扩展类转JSON
String json = mapper.writeValueAsString(userExpandVO);
return json;*/
// 新优化方法
JSONObject obj = JSONObject.fromObject(userExpandVO);
String json = obj.toString();
return json;
}
//String JSON转VO
public UserExpandVO jsonStrToVO(String jsonStr) throws JsonParseException, IOException, Exception{
//Old 方法
/*ObjectMapper mapper = new ObjectMapper();
UserExpandVO user = mapper.readValue(jsonStr, UserExpandVO.class);
return user;*/
//新优化方法
//(1)速度块但有弊端:当json数据的organOfcityId属性(int类型)为null时候,obj.getInt("organOfcityId")不能获取到值
/*JSONObject obj = JSONObject.fromObject(jsonStr);
UserExpandVO user = new UserExpandVO();
user.setManagerType(obj.getString("managerType"));
user.setStructureId(obj.getString("structureId"));
user.setHouseId(obj.getString("houseId"));
// user.setOrganOfcityId(obj.getInt("organOfcityId"));
user.setOffice(obj.getString("office"));
user.setUpLeaderId(obj.getString("upLeaderId"));
user.setRegName(obj.getString("regName"));
//解决该弊端
if("null".equals(obj.get("organOfcityId")+"")){
user.setOrganOfcityId(null);
}else{
user.setOrganOfcityId(obj.getInt("organOfcityId"));
}*/
(2)
JSONObject obj = new JSONObject().fromObject(jsonStr);
UserExpandVO user = (UserExpandVO)JSONObject.toBean(obj,UserExpandVO.class);
return user;
}
// 获取json数据对应实体类的某一个字段值
public Object getFeidFromJson(String jsonStr, String name) {// jsonStr:要转换的json字符串,name:需要的字段名称
JSONObject json = JSONObject.fromObject(jsonStr);
return json.get(name);
}
}
更多推荐
所有评论(0)