将Map <String,String>转换为POJO

我一直在看杰克逊,但似乎我必须将Map转换为JSON,然后将结果JSON转换为POJO。


有没有办法将Map直接转换为POJO?


BIG阳
浏览 1398回答 3
3回答

白衣非少年

嗯,你也可以用杰克逊实现这一点。(因为你考虑使用杰克逊,它似乎更舒服)。使用ObjectMapper的convertValue方法:final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapperfinal MyPojo pojo = mapper.convertValue(map, MyPojo.class);无需转换为JSON字符串或其他内容; 直接转换的速度要快得多。

森林海

Gson的解决方案:Gson gson = new Gson();JsonElement jsonElement = gson.toJsonTree(map);MyPojo pojo = gson.fromJson(jsonElement, MyPojo.class);

九州编程

我测试了Jackson和BeanUtils,发现BeanUtils要快得多。在我的机器(Windows8.1,JDK1.7)中,我得到了这个结果。BeanUtils t2-t1 = 286Jackson t2-t1 = 2203public class MainMapToPOJO {public static final int LOOP_MAX_COUNT = 1000;public static void main(String[] args) {&nbsp; &nbsp; Map<String, Object> map = new HashMap<>();&nbsp; &nbsp; map.put("success", true);&nbsp; &nbsp; map.put("data", "testString");&nbsp; &nbsp; runBeanUtilsPopulate(map);&nbsp; &nbsp; runJacksonMapper(map);}private static void runBeanUtilsPopulate(Map<String, Object> map) {&nbsp; &nbsp; long t1 = System.currentTimeMillis();&nbsp; &nbsp; for (int i = 0; i < LOOP_MAX_COUNT; i++) {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; TestClass bean = new TestClass();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; BeanUtils.populate(bean, map);&nbsp; &nbsp; &nbsp; &nbsp; } catch (IllegalAccessException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; } catch (InvocationTargetException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; long t2 = System.currentTimeMillis();&nbsp; &nbsp; System.out.println("BeanUtils t2-t1 = " + String.valueOf(t2 - t1));}private static void runJacksonMapper(Map<String, Object> map) {&nbsp; &nbsp; long t1 = System.currentTimeMillis();&nbsp; &nbsp; for (int i = 0; i < LOOP_MAX_COUNT; i++) {&nbsp; &nbsp; &nbsp; &nbsp; ObjectMapper mapper = new ObjectMapper();&nbsp; &nbsp; &nbsp; &nbsp; TestClass testClass = mapper.convertValue(map, TestClass.class);&nbsp; &nbsp; }&nbsp; &nbsp; long t2 = System.currentTimeMillis();&nbsp; &nbsp; System.out.println("Jackson t2-t1 = " + String.valueOf(t2 - t1));}}
打开App,查看更多内容
随时随地看视频慕课网APP