我一直在看杰克逊,但似乎我必须将地图转换为JSON,然后将结果JSON转换为POJO。
是否有方法将Map直接转换为POJO?
我一直在看杰克逊,但似乎我必须将地图转换为JSON,然后将结果JSON转换为POJO。
是否有方法将Map直接转换为POJO?
当前回答
ObjectMapper objectMapper = new ObjectMapper();
// Use this if all properties are not in the class
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
final MyPojo pojo = objectMapper.convertValue(map, MyPojo.class);
与第一个答案相同,但我得到了一个错误使用,因为我不希望Map的所有属性转换为类。我还找到了objectmap .configure(反序列化特性。FAIL_ON_UNKNOWN_PROPERTIES、假);作为解决方案。
其他回答
与Gson的解决方案:
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(map);
MyPojo pojo = gson.fromJson(jsonElement, MyPojo.class);
如果你的类中有泛型类型,你应该使用TypeReference和convertValue()。
final ObjectMapper mapper = new ObjectMapper();
final MyPojo<MyGenericType> pojo = mapper.convertValue(map, new TypeReference<MyPojo<MyGenericType>>() {});
你也可以用它把pojo转换回java.util.Map。
final ObjectMapper mapper = new ObjectMapper();
final Map<String, Object> map = mapper.convertValue(pojo, new TypeReference<Map<String, Object>>() {});
杰克逊也能做到这一点。(而且自从你考虑使用jackson后,它似乎更舒服)。
使用ObjectMapper的convertValue方法:
final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
final MyPojo pojo = mapper.convertValue(map, MyPojo.class);
不需要转换成JSON字符串或其他东西;直接转换要快得多。
ObjectMapper objectMapper = new ObjectMapper();
// Use this if all properties are not in the class
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
final MyPojo pojo = objectMapper.convertValue(map, MyPojo.class);
与第一个答案相同,但我得到了一个错误使用,因为我不希望Map的所有属性转换为类。我还找到了objectmap .configure(反序列化特性。FAIL_ON_UNKNOWN_PROPERTIES、假);作为解决方案。
我对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));
}}