项目搭建中利用泛型和反射机制创建一些公用的工具方法处理特定的数据接口转换
常规的转换用Gson就可以了
/**<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
*/
import com.google.gson.Gson;
new Gson().fromJson(source,Map.class)
自定义的时候可以参考一下方法,也方便理解Gson等供应商提供的工具类原码原理
/**
* 数据结构转换
*/
public class MetaClassUtil {
/**
* map转对象
* 把source转为target
* @param source source 数据源
* @param target target 需要转换的类型
* @param <T> 返回值类型
* @return 返回值
* @throws Exception newInstance可能会抛出的异常
*/
public static <T> T mapToObj(Map source,Class<T> target) throws Exception {
//获取T所有的属性名
//import java.lang.reflect.Field;
Field[] fields = target.getDeclaredFields();
//创建一个示例对象
T object = target.newInstance();
for(Field field:fields){
Object val;
if((val=getContainsKeyToMap(source, field.getName()))!=null){
field.setAccessible(true);
//field.set(object ,val);底层做了Object转换成field的类型
field.set(object ,val);
}
}
return object ;
}
/**
* 根据属性名获取map中的value
*/
private static Object getContainsKeyToMap(Map map, String propertyName) {
if (map == null || map.isEmpty() || propertyName == null) {
return null;
}
if (map.containsKey(propertyName)){
return map.get(propertyName);
}
/*
下划线和驼峰匹自由组合匹配不了的方式
propertyName Key
下划线- 驼峰
驼峰- 下划线
*/
/*
下划线-驼峰
*/
if (propertyName.contains("_")){
//下划线转 驼峰式命名法
String toCamelCase = toCamelCase(propertyName);
if (map.containsKey(toCamelCase)){
return map.get(toCamelCase);
}
}
/*
驼峰-下划线
*/
Set set = map.entrySet();
Iterator it = set.iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
if (entry.getKey().contains("_")){
//下划线转 驼峰式命名法
String toCamelCase = toCamelCase(entry.getKey());
if (toCamelCase.equals(propertyName)){
return entry.getValue();
}
}
}
return null;
}
/**
*下划线转 驼峰式命名法
*/
public static String toCamelCase(String s) {
if (s == null) {
return null;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == "_".charAt(0)) {
upperCase = true;
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
} else {
sb.append(c);
}
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
Map<String,Object> source=new HashMap<>();
source.put("user_name","张三");
//source.put("userName","李四");
source.put("age",1);
//map转为对象
Person person = mapToObj(source,Person.class);
System.out.println(person.toString());
//输出结果:Person{userName='张三', age=1}
}
}
用于测试的类
public class Person {
private String userName;
private int age;
public String getUserName() {
return userName;
}
public int getAge() {
return age;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"userName='" + userName + '\'' +
", age=" + age +
'}';
}
}