1.實體類轉JsonObject、JsonArray
//Student student = new Student();
//student爲實體類對象,格式爲json
//Course爲學生類下課程類,屬於一對多
//使用的是阿里下的com.alibaba.fastjson包
JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(student));
Map<String,Object> map = (Map<String,Object>)jsonObject;
String errMsg = (String) map.get("errMsg");
String ext = (String) map.get("ext");
Integer code = (Integer) map.get("result");
Object courses = map.get("details");
List<Course> list = JSONObject.parseArray(courses.toString(), Course.class);
2.json字符串轉實體類
//jsonString爲json字符串對象
//import com.alibaba.fastjson.*;
Student student = null;
try {
//因爲接收到的消息可能轉化異常,需要捕獲
student = JSON.parseObject(jsonString, new TypeReference<Student>() {);
} catch (JSONException e) {
//異常處理
}
3.Map轉換實體對象
org.apache.commoms.beanutils.BeanUtils.populate(實體對象, Map集合)