记录:265
场景:Java对象转换为Map;Map转换为Java对象;Map转换为Json字符串。
本例环境:JDK 1.8
1.Java对象转换为Map
普通java对象的属性和属性值,转换为Map的Key和Value。
方法:
public static Mapobject2Map(Object obj) throws Exception { Map map = new HashMap (); Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); map.put(field.getName(), field.get(obj)); } return map; }
测试:
GirlInfo girlInfo2 = new GirlInfo("小州",Double.valueOf("165"), Double.valueOf("102"),"C","杭州"); Mapmap2 = MapToObjectUtils.object2Map(girlInfo2);
2.Map转换为Java对象
Map的Key和Value转换为普通java对象的属性和属性值。
方法:
public staticT map2Object(Map map, Class clazz) { if (map == null) { return null; } T obj = null; try { obj = clazz.newInstance(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { int modifiers = field.getModifiers(); //判断Static属性或者Final属性 if (Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers)) { continue; } else { //设置为true后,反射即可访问私有变量 field.setAccessible(true); field.set(obj, map.get(field.getName())); }} } catch (Exception e) { e.printStackTrace(); } return obj; }
测试:
Mapmap = new HashMap (); map.put("name","小杭"); map.put("height",Double.valueOf("162")); map.put("weight",Double.valueOf("100")); map.put("cup","B"); map.put("city","杭州"); GirlInfo girlInfo = MapToObjectUtils.map2Object(map,GirlInfo.class);
3.Map转换为Json字符串
Map的Key和Value转换为JSON字符串格式。
方法:
public static String mapToJsonString(Map map){ JSonObject json = new JSonObject(); Iterator> entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = entries.next(); json.put(entry.getKey(),entry.getValue()); } return json.toString(); }
测试:
Mapmap3 = new HashMap (); map3.put("name","小杭"); map3.put("height",Double.valueOf("162")); map3.put("weight",Double.valueOf("100")); map3.put("cup","B"); map3.put("city","杭州"); String result = MapToObjectUtils.mapToJsonString(map3);
数据格式:
{ "city":"杭州", "name":"小杭", "weight":100.0, "height":162.0, "cup":"B" }
4.实体类GirlInfo
测试中使用到的GirlInfo类
public class GirlInfo implements Serializable { private String name; private Double height; private Double weight; private String cup; private String city; public GirlInfo(){} public GirlInfo(String name,Double height, Double weight,String cup,String city){ this.name = name; this.height = height; this.weight = weight; this.cup=cup; this.city = city; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getHeight() { return height; } public void setHeight(Double height) { this.height = height; } public Double getWeight() { return weight; } public void setWeight(Double weight) { this.weight = weight; } public String getCup() { return cup; } public void setCup(String cup) { this.cup = cup; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
以上,感谢。
2021年12月16日
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)