处理实体与map,json之间的转换
实体与Map<String,Object>的转换
直接看代码,如下:
package com.liu;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Description: Map与实体之间的转换 以及 String如何转Map<String, Object>
* @author liusx
* @date 2021-7-20
*/
@SuppressWarnings("all")
public class MapAndEntyUtil {
public static final char UNDERLINE='_';
/**
* @Description: 实体对象转成Map
* @param obj
* @return Map<String,Object> 返回类型
* @author liusx
* @date 2021-7-20
*/
public static Map<String, Object> entityToMap(Object obj) {
Map<String, Object> map = new HashMap<>();
if (obj == null) {
return map;
}
Class clasz = obj.getClass();
Field[] fields = clasz.getDeclaredFields();
try {
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
/**
* @Description: Map转成实体对象
* @param map 这里map的key值要求与实体的属性命名保持一致,
* 备注:如果map里的key值是数据库的字段,此方法不使用,应先做驼峰处理
* @param clasz
* @return Object 返回类型
* @author liusx
* @date 2021-7-20
*/
public static Object mapToEntity(Map<String, Object> map, Class<?> clasz) {
if (map == null) {
return null;
}
Object obj = null;
try {
obj = clasz.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
/**
* @Description: 将传来的参数去掉"_",并驼峰处理
* @param o
* @return String 返回类型
* @author liusx
* @date 2021-7-20
*/
public static String underlineToCamel(Object o){
String param = (o == null)?"":o.toString();
if ("".equals(param.trim())){
return "";
}
int len=param.length();
StringBuilder sb=new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c=param.charAt(i);
if (c==UNDERLINE){
if (++i<len){
sb.append(Character.toUpperCase(param.charAt(i)));
}
}else{
sb.append(c);
}
}
return sb.toString();
}
/**
* @Description: 将List<Map<String, Object>>类型里含有下划线"_"的list转换为不含
* @param <T>
* @param list
* @param clazz
* @return List<T> 返回类型
* @author liusx
* @date 2021-7-20
*/
public static <T> List<T> getObjectList(List<Map<String, Object>> list,Class<?> clazz) {
if(list != null && list.size()>0) {
List<T> listResult = new ArrayList<T>();
for(int i=0;i<list.size();i++) {
//1.如果map里的key是数据库的字段,去掉"_"
String mapStr = underlineToCamel(list.get(i));
//2.将mapStr重新转换为map形式(Map<String, Object>)
Map<String, Object> map = getMapByStr2(mapStr);
System.out.println("map==="+map);
//3.将map转换为实体,放入list
listResult.add((T) mapToEntity(map, clazz));
}
return listResult;
}else {
return null;
}
}
/**
* @Description: 将字符串转换为Map<String, Object>形式
* @param mapStr
* @return
* @return Map<String,Object> 返回类型
* @author liusx
* @date 2021-7-20
* 备注:返回的map里的vaue都是string类型
*/
public static Map<String, Object> getMapByStr(String mapStr) {
Map<String, Object> map = new HashMap<>();
if(mapStr!=null){
String str = "";
String key = "";
Object value = "";
char[] charList = mapStr.toCharArray();
boolean valueBegin = false;
for (int i = 0; i < charList.length; i++) {
char c = charList[i];
if (c == '{') {
if (valueBegin == true) {
value = getMapByStr(mapStr.substring(i, mapStr.length()));
i = mapStr.indexOf('}', i) + 1;
map.put(key, value);
}
} else if (c == '=') {
valueBegin = true;
key = str;
str = "";
} else if (c == ',') {
valueBegin = false;
value = str;
str = "";
map.put(key, value);
} else if (c == '}') {
if (str != "") {
value = str;
}
map.put(key, value);
return map;
} else if (c != ' ') {
str += c;
}
}
return map;
}else {
return map;
}
}
/**
* @Description: 将字符串转换为Map<String, Object>形式
* @param mapStr
* @return Map<String,Object> 返回类型
* @author liusx
* @date 2021-7-20
* 备注:返回的map里的vaue都是string类型
*/
public static Map<String, Object> getMapByStr2(String mapStr) {
Map<String, Object> resultMap = new HashMap<String, Object>();
mapStr = (mapStr == null)?"":mapStr;
if ("".equals(mapStr.trim())){
return resultMap;
}else {
mapStr = mapStr.replace("{", "").replace("}", "");
String[] resultMapStr = mapStr.split(",");
for (String rs : resultMapStr) {
//System.out.println("rs:" + rs);
String[] kv = rs.split("=");
resultMap.put(kv[0], kv[1]);
}
return resultMap;
}
}
}
package com.liu;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
public class TestMapEntyList {
public static void main(String[] args) {
Map<String, Object> map1 = new HashMap<>();
map1.put("stu_Id", 10001);
map1.put("stu_Name", "小花");
Map<String, Object> map2 = new HashMap<>();
map2.put("stu_Id", 10002);
map2.put("stu_Name", "小花2");
List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
list.add(map1);
list.add(map2);
System.out.println(list);
List<Student> listStu = MapAndEntyUtil.getObjectList(list, Student.class);
System.out.println(listStu);
}
}
将实体或者list格式与json的格式之间的转换
代码如下:
package com.liu;
import java.util.List;
import org.apache.poi.ss.formula.functions.T;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @Description: 将实体或者list格式与json的格式之间的转换
* @author liusx
* @date 2021-7-20
*/
public class JsonAndEntyUtil {
/**
* @Description: 将传入类型,转化为json格式
* @param o
* @param clazz
* @return String 返回类型
* @author liusx
* @date 2021-7-20
*/
public static String getJsonByObject(Object o) {
if(o != null) {
ObjectMapper objMapper = new ObjectMapper();
String jsonResult = "";
try {
jsonResult = objMapper.writeValueAsString(o);
//System.out.println("jsonResult==="+jsonResult);
return jsonResult;
} catch (JsonProcessingException e) {
e.printStackTrace();
return "";
}
}else {
return "";
}
}
/**
* @Description: 将传入格式通过中间json的转换,转化为实体list格式
* @param <T>
* @param o
* @param clazz
* @return List<T> 返回类型
* @author liusx
* @date 2021-7-20
* eg:
* param:[{stu_Id=10001, stu_Name=小花, age=18}, {stu_Id=10002, stu_Name=小花2, age=19}]
* return:[Student [stuId=10001, age=18, stuName=小花, stuPwd=null], Student [stuId=10002, age=19, stuName=小花2, stuPwd=null]]
*/
public static <T> List<T> getObjectList(Object o,Class<T> clazz) {
if(o != null) {
ObjectMapper objMapper = new ObjectMapper();
String jsonResult = "";
try {
jsonResult = objMapper.writeValueAsString(o);
//System.out.println("jsonResult==="+jsonResult);
List<T> list = JSON.parseArray(jsonResult.toString(),clazz);
//System.out.println("list::::"+list);
return list;
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}else {
return null;
}
}
}
package com.liu;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TestJsonList {
public static void main(String[] args) {
Map<String, Object> map1 = new HashMap<>();
map1.put("stu_Id", 10001);
map1.put("stu_Name", "小花");
map1.put("age", 18);
Map<String, Object> map2 = new HashMap<>();
map2.put("stu_Id", 10002);
map2.put("stu_Name", "小花2");
map2.put("age", 19);
List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
list.add(map1);
list.add(map2);
System.out.println(list);
List<Student> listStu = JsonAndEntyUtil.getObjectList(list, Student.class);
System.out.println("listStu::::"+listStu);
}
}
实体代码如下:
package com.liu;
public class Student {
private String stuId;
private String age;
private String stuName;
private String stuPwd;
public String getStuId() {
return stuId;
}
public void setStuId(String stuId) {
this.stuId = stuId;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuPwd() {
return stuPwd;
}
public void setStuPwd(String stuPwd) {
this.stuPwd = stuPwd;
}
@Override
public String toString() {
return "Student [stuId=" + stuId + ", age=" + age + ", stuName=" + stuName + ", stuPwd=" + stuPwd + "]";
}
}
.参考链接如下:
链接: link.