java字符串转map

发布时间:2024-11-11 18:04

packagecom.home.app.common.utils;importcom.fasterxml.jackson.annotation.JsonInclude.Include;importcom.fasterxml.jackson.core.JsonProcessingException;importcom.fasterxml.jackson.databind.ObjectMapper;importcom.fasterxml.jackson.databind.SerializationFeature;importjava.lang.reflect.Field;importjava.lang.reflect.Modifier;importjava.util.LinkedHashMap;importjava.util.Map;/***@authorBinary Wang*/

public classJsonUtils {private static final ObjectMapper JSON = newObjectMapper();static{

JSON.setSerializationInclusion(Include.NON_NULL);

JSON.configure(SerializationFeature.INDENT_OUTPUT, Boolean.TRUE);

}public staticString toJson(Object obj) {try{returnJSON.writeValueAsString(obj);

}catch(JsonProcessingException e) {

e.printStackTrace();

}return null;

}/*** Object转Map

*@paramobj

*@return

*/

public static MapgetObjectToMap(Object obj) {

Map map = new LinkedHashMap();

Class> clazz =obj.getClass();

System.out.println(clazz);for(Field field : clazz.getDeclaredFields()) {

field.setAccessible(true);

String fieldName=field.getName();

Object value= null;try{

value=field.get(obj);

}catch(IllegalAccessException e) {

e.printStackTrace();

}if (value == null){

value= "";

}

map.put(fieldName, value);

}returnmap;

}//Map转Object

public static Object getMapToObject(Map map, Class>beanClass) {if (map == null)return null;

Object obj= null;try{

obj=beanClass.newInstance();

}catch(InstantiationException e) {

e.printStackTrace();

}catch(IllegalAccessException e) {

e.printStackTrace();

}

Field[] fields=obj.getClass().getDeclaredFields();for(Field field : fields) {int mod =field.getModifiers();if (Modifier.isStatic(mod) ||Modifier.isFinal(mod)) {continue;

}

field.setAccessible(true);if(map.containsKey(field.getName())) {try{

field.set(obj, map.get(field.getName()));

}catch(IllegalAccessException e) {

e.printStackTrace();

}

}

}returnobj;

}

}

网址:java字符串转map https://www.yuejiaxmz.com/news/view/35902

相关内容

【Java数据结构】字符串常量池
Java解决if(!=null)臭名昭著的判空处理(Optional)
经典String str = new String(“abc”)创建了几个对象?(转)
MATLAB图像处理(包括图像类型转换)
基于java web个人财务管理系统
基于Java+SpringBoot+Vue+HTML5膳食营养健康网站(源码+LW+调试文档+讲解等)/膳食搭配/营养建议/健康生活/网站推荐/营养学/饮食指南/健康饮食/营养食谱/膳食计划/健康膳食
基于java+ssm+jsp的个人财务管理系统
省时省力,这些Python高效代码片段必须牢记
【Java报错已解决】Driver class ‘net.sourceforge.jtds.jdbc.Driver’ could not be found, make sure the
【Java】基础类型之float(八)

随便看看