Convert a Map<String, String> to a POJO

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

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?

回答1:

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.



回答2:

A solution with Gson:

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


回答3:

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 


回答4:

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).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!