Last active
June 26, 2018 06:34
-
-
Save lonly197/5915ff68c0a043ada66220476eb9b0e3 to your computer and use it in GitHub Desktop.
提供一个工具咧,通过@fieldmap标注来识别,把前端传过来的json,在@requestbody转的对象后,再转为Map对象
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.base.CaseFormat; | |
import com.google.common.base.Preconditions; | |
import com.google.common.collect.Maps; | |
import java.beans.BeanInfo; | |
import java.beans.Introspector; | |
import java.beans.PropertyDescriptor; | |
import java.lang.reflect.Method; | |
import java.time.LocalDateTime; | |
import java.time.format.DateTimeFormatter; | |
import java.util.List; | |
import java.util.Map; | |
/** | |
* Created by lonly on 2018/6/26. | |
*/ | |
public class MapUtils { | |
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); | |
public static Map<String, Object> objTransformMap(Object object, List<String> skipStrs) throws Exception { | |
Preconditions.checkNotNull(object, "object must not be null !"); | |
Map<String, Object> map = Maps.newHashMap(); | |
BeanInfo info = Introspector.getBeanInfo(object.getClass()); | |
for (PropertyDescriptor pd : info.getPropertyDescriptors()) { | |
Method reader = pd.getReadMethod(); | |
if (reader != null | |
&& (skipStrs == null || !skipStrs.contains(pd.getName())) | |
&& !pd.getName().equals("class")) { | |
Object value = reader.invoke(object); | |
value = value instanceof LocalDateTime ? ((LocalDateTime) value).format(DATE_TIME_FORMATTER) : value; | |
if (value != null) { | |
map.put(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, pd.getName()), value); | |
} | |
} | |
} | |
return map; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment