将一个Map <String,String>转换为一个POJO

我一直在看jackson,但似乎我将不得不将地图转换为JSON,然后将结果JSON转换为POJO。

有没有办法将一个Map直接转换成POJO?

那么,jackson也可以做到这一点。 (因为你正在考虑使用jackson似乎更舒服)。

使用ObjectMapperconvertValue方法:

 final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper final MyPojo pojo = mapper.convertValue(map, MyPojo.class); 

不需要转换成JSONstring或其他东西; 直接转换确实快得多。

Gson的解决scheme:

 Gson gson = new Gson(); JsonElement jsonElement = gson.toJsonTree(map); MyPojo pojo = gson.fromJson(jsonElement, MyPojo.class); 

是的,它绝对有可能避免中间转换为JSON。 使用Dozer这样的深度复制工具,您可以直接将地图转换为POJO。 这是一个简单的例子:

示例POJO:

 public class MyPojo implements Serializable { private static final long serialVersionUID = 1L; private String id; private String name; private Integer age; private Double savings; public MyPojo() { super(); } // Getters/setters @Override public String toString() { return String.format( "MyPojo[id = %s, name = %s, age = %s, savings = %s]", getId(), getName(), getAge(), getSavings()); } } 

示例转换代码:

 public class CopyTest { @Test public void testCopyMapToPOJO() throws Exception { final Map<String, String> map = new HashMap<String, String>(4); map.put("id", "5"); map.put("name", "Bob"); map.put("age", "23"); map.put("savings", "2500.39"); map.put("extra", "foo"); final DozerBeanMapper mapper = new DozerBeanMapper(); final MyPojo pojo = mapper.map(map, MyPojo.class); System.out.println(pojo); } } 

输出:

MyPojo [id = 5,name = Bob,年龄= 23,储蓄= 2500.39]

注意:如果您将源映射更改为Map<String, Object>则可以复制任意深度的嵌套属性(使用Map<String, String>只能获得一个级别)。

我已经testing了Jackson和BeanUtils,发现BeanUtils要快得多。
在我的机器(Windows8.1,JDK1.7)我得到了这个结果。

 BeanUtils t2-t1 = 286 Jackson t2-t1 = 2203 

 public class MainMapToPOJO { public static final int LOOP_MAX_COUNT = 1000; public static void main(String[] args) { Map<String, Object> map = new HashMap<>(); map.put("success", true); map.put("data", "testString"); runBeanUtilsPopulate(map); runJacksonMapper(map); } private static void runBeanUtilsPopulate(Map<String, Object> map) { long t1 = System.currentTimeMillis(); for (int i = 0; i < LOOP_MAX_COUNT; i++) { try { TestClass bean = new TestClass(); BeanUtils.populate(bean, map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } long t2 = System.currentTimeMillis(); System.out.println("BeanUtils t2-t1 = " + String.valueOf(t2 - t1)); } private static void runJacksonMapper(Map<String, Object> map) { long t1 = System.currentTimeMillis(); for (int i = 0; i < LOOP_MAX_COUNT; i++) { ObjectMapper mapper = new ObjectMapper(); TestClass testClass = mapper.convertValue(map, TestClass.class); } long t2 = System.currentTimeMillis(); System.out.println("Jackson t2-t1 = " + String.valueOf(t2 - t1)); }}