将 LinkedHashMap 转换为复杂对象 [英] Casting LinkedHashMap to Complex Object
问题描述
我有一个应用程序,它使用 Jackson 将我的复杂对象编组到 JSON 中,在 DynamoDB 中存储一些数据.
I've got an application that stores some data in DynamoDB using Jackson to marshall my complex object into a JSON.
例如,我正在编组的对象可能如下所示:
For example the object I'm marshalling might look like this:
private String aString;
private List<SomeObject> someObjectList;
SomeObject 可能如下所示:
Where SomeObject might look like this:
private int anInteger;
private SomeOtherObject;
和 SomeOtherObject 可能看起来像这样:
and SomeOtherObject might look like this:
private long aLong;
private float aFloat;
这很好,对象被编组没有问题并作为 JSON 字符串存储在数据库中.
This is fine an the object gets marshalled no problem and stored in the DB as a JSON string.
当需要从 DynamoDB 检索数据时,Jackson 会自动检索 JSON 并将其转换回......除了someObjectList"作为 List
返回,而不是作为 >List
!这是杰克逊的标准行为,发生这种情况并非错误.
When it comes time to retrieve the data from DynamoDB Jackson automatically retrieves the JSON and converts it back... EXCEPT that 'someObjectList' is returned as a List<LinkedHashMap>
not as a List<SomeObject>
! This is standard behaviour for Jackson, its not a mistake that this is happening.
所以现在这导致了一个问题.我的代码库认为它处理的是 List
但实际情况是它处理的是 List
!我的问题是如何将 LinkedHashMap 恢复为SomeObject".显然这是一个手动过程,但我的意思是我什至无法提取值.
So now this leads to a problem. My code base thinks its dealing with a List<SomeObject>
but the reality is that its handling a List<LinkedHashMap>
! My question is how do I get my LinkedHashMap back into a 'SomeObject'. Obviously this is a manual process but what I mean is I can't even extract the values.
如果我这样做:
for (LinkedHashMap lhm : someObjectList) {
// Convert the values back
}
我收到一个编译错误,告诉我 someObjectList 的类型是SomeObject"而不是 LinkedHashMap.
I get a compile error telling me that someObjectList is of type 'SomeObject' not LinkedHashMap.
如果我这样做:
for (SomeObject lhm : someObjectList) {
// Convert the values back
}
我收到一个运行时错误,告诉我 LinkedHashMap 无法转换为SomeObject".
I get a runtime error telling me that LinkedHashMap cannot be cast to 'SomeObject'.
推荐答案
您可以使用 ObjectMapper.convertValue()
,一个值一个值,甚至整个列表.但是你需要知道要转换成的类型:
You can use ObjectMapper.convertValue()
, either value by value or even for the whole list. But you need to know the type to convert to:
POJO pojo = mapper.convertValue(singleObject, POJO.class);
// or:
List<POJO> pojos = mapper.convertValue(listOfObjects, new TypeReference<List<POJO>>() { });
这在功能上和你一样:
byte[] json = mapper.writeValueAsBytes(singleObject);
POJO pojo = mapper.readValue(json, POJO.class);
但避免将数据实际序列化为 JSON,而是使用内存中的事件序列作为中间步骤.
but avoids actual serialization of data as JSON, instead using an in-memory event sequence as the intermediate step.
这篇关于将 LinkedHashMap 转换为复杂对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!