I've been looking at Jackson, but is seems I would have to convert the Map to JSON, and then the resulting JSON to the POJO.
Is there a way to convert a Map directly to a POJO?
I've been looking at Jackson, but is seems I would have to convert the Map to JSON, and then the resulting JSON to the POJO.
Is there a way to convert a Map directly to a POJO?
Well, you can achieve that with Jackson, too. (and it seems to be more comfortable since you were considering using jackson).
Use ObjectMapper's convertValue method:
final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper final MyPojo pojo = mapper.convertValue(map, MyPojo.class); No need to convert into JSON string or something else; direct conversion does much faster.
A solution with Gson:
Gson gson = new Gson(); JsonElement jsonElement = gson.toJsonTree(map); MyPojo pojo = gson.fromJson(jsonElement, MyPojo.class); I have tested both Jackson and BeanUtils and found out that BeanUtils is much faster.
In my machine(Windows8.1 , JDK1.7) I got this result.
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 map = new HashMap(); map.put("success", true); map.put("data", "testString"); runBeanUtilsPopulate(map); runJacksonMapper(map); } private static void runBeanUtilsPopulate(Map map) { long t1 = System.currentTimeMillis(); for (int i = 0; i map) { long t1 = System.currentTimeMillis(); for (int i = 0; i Yes, its definitely possible to avoid the intermediate conversion to JSON. Using a deep-copy tool like Dozer you can convert the map directly to a POJO. Here is a simplistic example:
Example 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()); } } Sample conversion code:
public class CopyTest { @Test public void testCopyMapToPOJO() throws Exception { final Map map = new HashMap(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); } } Output:
MyPojo[id = 5, name = Bob, age = 23, savings = 2500.39]
Note: If you change your source map to a Map then you can copy over arbitrarily deep nested properties (with Map you only get one level).