使用Jackson实现Map与Bean互转
在使用 java 开发中,通常需要把 Map 转成 Bean,或把 Bean 转成 Map,这就用的工具类,在此推荐使用import com.fasterxml.jackson.databind.ObjectMapper;
包下的ObjectMapper
类,比 JsonObject 效率高,下面就列举了几种使用方法。
1.pom.xml
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.6</version> <scope>compile</scope> </dependency>
2.java 代码
package com.jin.demo.jackson; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.HashMap; import java.util.Map; /** * 使用 Jackson工具 * map to bean * bean to map * * @auther jinsx * @date 2019-03-26 16:37 */ public class JacksonTest { private static final ObjectMapper mapper = new ObjectMapper(); public static void main(String[] args) throws Exception { // 测试 将Map转成指定的Bean Map<String, Object> map = new HashMap<>(); map.put("name", "张三"); Person o = (Person)JacksonTest.mapToBean(map, Person.class); System.out.println(o); // 测试 将Bean转成Map Person person = new Person(); person.setAge(18); Map map1 = JacksonTest.beanToMap(person); System.out.println(map1); } // 将对象转成字符串 public static String objectToString(Object obj) throws Exception { return mapper.writeValueAsString(obj); } // 将Map转成指定的Bean public static Object mapToBean(Map map, Class clazz) throws Exception { return mapper.readValue(objectToString(map), clazz); } // 将Bean转成Map public static Map beanToMap(Object obj) throws Exception { return mapper.readValue(objectToString(obj), Map.class); } }
3.Person 类
package com.jin.demo.jackson; import java.io.Serializable; import java.util.Date; /** * @auther jinsx * @date 2019-03-26 17:30 */ public class Person implements Serializable { private int age; private String name; private Date birthday; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { return "Person{" + "age=" + age + ", name='" + name + '\'' + ", birthday=" + birthday + '}'; } }
转: https://blog.csdn.net/axing2015/article/details/88827053