fastjson场景

json转java对象

// 将Json字符串通过fastjson转为JSONObject对象
JSONObject jsonObject = JSONObject.parseObject(userJson);
// 将JSONObject对象转为Object实体对象
UserBean user = JSON.toJavaObject(jsonObject, UserBean.class);

java转jsonobject对象

JSONObject jsonObject = (JSONObject) JSONObject.toJSON(new UserBean());

list转json

 List list = new ArrayList(16);
JSONObject result = JSONObject.parseObject(JSONObject.toJSONString(list));

对象与String互相转换

//将对象转换成为字符串 
String strUserInfo = JSON.toJSONString(UserInfo); 
//字符串转换成为对象 
InfoDo UserInfo = JSON.parseObject(strUserInfo, UserInfo.class);

对象转list

//将对象集合转换成为字符串 
String users = JSON.toJSONString(users); 
//将字符串转换成为对象集合
 List userList = JSON.parseArray(userStr, User.class);

String与json互相转换

//String 转 Json对象 
JSONObject jsonObject = JSONObject.parseObject(str);
//json对象转string 
String jsonString = jsonObject.toJSONString();// jsonObject为JSON对象

map与String互相转换

//字符串转jsonObject
JSONObject  jsonObject = JSONObject.parseObject(str);
//json对象转Map
 Map<String,Object> map = (Map<String,Object>)jsonObject;
 //map转字符串 
String jsonString = JSON.toJSONString(map);

map转json

//map转json对象
Map<String,Object> map = new HashMap<>();
map.put("age", 23);
map.put("name", "Jacky");
JSONObject json = new JSONObject(map);
//json对象转Map 
Map<String,Object> map = (Map<String,Object>)jsonObject;

map<String,Object>转list<T>

/** 
* 将List<map>转换成List<java对象>
* */
public static <T> List<T> getListObject(List<Map<String,Object>> list,Class<T> cls){
     List<T> paramList = new ArrayList<>();
     if (CollectionUtils.isNotEmpty(list)){
        for (Map<String, Object> map : list) {
             paramList.add(this.parseMapObject(map,cls));        
        }    
     }    
     return paramList;
}
/** 
* 将map转换成java对象 
* */
public static <T> T parseMapObject(Map<String,Object> paramMap, Class<T> cls) {
    return JSONObject.parseObject(JSONObject.toJSONString(paramMap),cls);
}

 String转jsonArray

String review = "[
{ 
"name":"人员A",
"review_grades":{ 
"name":"优秀",
"parent":"-1","key":"1"},
"remark":"XXX今年XXX获得优秀党员称号"},
{ 
"name":"人员B",
"review_grades":{ 
"name":"合格",
"parent":"-1","key":"2"},
"remark":"表现良好"}]";
JSONArray tableData = JSONArray.parseArray(review);

jsonArray转list

List<DemocracyReviewVO> ls = arr.toJavaList(DemocracyReviewVO.class);

  

posted @ 2023-02-10 17:18  a快乐码农  阅读(15)  评论(0编辑  收藏  举报