如何在Java中将POJO转换为Map,反之亦然?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39543926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:13:56  来源:igfitidea点击:

How to convert POJO to Map and vice versa in Java?

java

提问by Anindya Chatterjee

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.

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

I am using gson to convert POJO to json,

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

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

then

然后

Document doc = Document.parse(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.

创建文档,这很容易。但其他方式是有问题的。document.toJson()在反序列化到 POJO 时,gson 没有给出标准的 json 长、时间戳等。所以我需要一种将 org.bson.Document 转换为标准 json 的方法。

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

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

采纳答案by cassiomolin

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

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

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

你可以使用 Hymanson,一个流行的 Java JSON 解析器:

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

According to the Hymanson 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.

根据 Hymanson文档,此方法在功能上类似于首先将给定值序列化为 JSON,然后将 JSON 数据绑定到给定类型的值,但应该更有效,因为完全序列化不会(需要)发生。但是,将使用相同的转换器(串行器和解串器)作为数据绑定,这意味着相同的对象映射器配置工作。