如何在Java中将POJO转换为Map,反之亦然? [英] How to convert POJO to Map and vice versa in Java?

查看:842
本文介绍了如何在Java中将POJO转换为Map,反之亦然?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的用例是将任意POJO转换为Map,然后从Map转换回POJO.所以我最终使用了策略POJO-> json-> org.bson.Document,然后回到org.bson.Document-> json-> POJO.

My use case is to convert any arbitrary POJO to Map and back from Map to POJO. So I ended up using the strategy POJO -> json -> org.bson.Document and back to org.bson.Document -> json -> POJO.

我正在使用gson将POJO转换为json,

I am using gson to convert POJO to json,

Gson gson = new GsonBuilder().create();
String json = gson.toJson(pojo);

然后

Document doc = Document.parse(json); 

创建文档很容易.但是其他方法是有问题的. document.toJson()长时间不提供标准json,时间戳等,并且gson在反序列化到POJO时抱怨.因此,我需要一种将org.bson.Document转换为标准json的方法.

to create the document and it is easy. But other way around is problematic. document.toJson() is not giving standard json for long, timestamp etc and gson is complaining while deserialising to POJO. So I need a way to convert org.bson.Document to standard json.

注意:我想避免使用mongo java驱动程序或morphia,因为这项工作无论如何与mongo无关.

NOTE: I want to avoid using mongo java driver or morphia as this work does not relate to mongo in anyway.

推荐答案

我的用例是将任意POJO转换为Map,然后从Map转换回POJO.

My use case is to convert any arbitrary POJO to Map and back from Map to POJO.

您可以使用Jackson,Java的流行JSON解析器:

You could use Jackson, a popular JSON parser for Java:

ObjectMapper mapper = new ObjectMapper();

// Convert POJO to Map
Map<String, Object> map = 
    mapper.convertValue(foo, new TypeReference<Map<String, Object>>() {});

// Convert Map to POJO
Foo anotherFoo = mapper.convertValue(map, Foo.class);

根据Jackson的

According to the Jackson documentation, this method is functionally similar to first serializing given value into JSON, and then binding JSON data into value of given type, but should be more efficient since full serialization does not (need to) occur. However, same converters (serializers and deserializers) will be used as for data binding, meaning same object mapper configuration works.

这篇关于如何在Java中将POJO转换为Map,反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆