将LinkedHashMap转换为复杂对象

tar*_*rka 51 java casting linkedhashmap jackson

我有一个应用程序,它使用Jackson将一些数据存储在DynamoDB中,以便将我的复杂对象编组为JSON.

例如,我正在编组的对象可能如下所示:

private String aString;
private List<SomeObject> someObjectList;
Run Code Online (Sandbox Code Playgroud)

SomeObject可能如下所示:

private int anInteger;
private SomeOtherObject;
Run Code Online (Sandbox Code Playgroud)

和SomeOtherObject可能如下所示:

private long aLong;
private float aFloat; 
Run Code Online (Sandbox Code Playgroud)

这很好,对象被编组没有问题,并作为JSON字符串存储在DB中.

当需要从DynamoDB检索数据时,Jackson会自动检索JSON并将其转换回来...除了'someObjectList'返回的List<LinkedHashMap>不是List<SomeObject>!这是杰克逊的标准行为,这不是一个错误.

所以现在这会导致问题.我的代码库认为它处理一个List<SomeObject>但现实是它处理一个List<LinkedHashMap>!我的问题是如何让我的LinkedHashMap回到'SomeObject'.显然这是一个手动过程,但我的意思是我甚至无法提取值.

如果我这样做:

for (LinkedHashMap lhm : someObjectList) {
    // Convert the values back
}
Run Code Online (Sandbox Code Playgroud)

我收到一个编译错误,告诉我someObjectList的类型为'SomeObject'而不是LinkedHashMap.

如果我这样做:

for (SomeObject lhm : someObjectList) {
    // Convert the values back
}
Run Code Online (Sandbox Code Playgroud)

我收到运行时错误,告诉我LinkedHashMap无法转换为'SomeObject'.

Sta*_*Man 127

您可以使用ObjectMapper.convertValue()值,也可以使用整个列表.但您需要知道要转换为的类型:

POJO pojo = mapper.convertValue(singleObject, POJO.class);
// or:
List<POJO> pojos = mapper.convertValue(listOfObjects, new TypeReference<List<POJO>>() { });
Run Code Online (Sandbox Code Playgroud)

这在功能上与您一样:

byte[] json = mapper.writeValueAsBytes(singleObject);
POJO pojo = mapper.readValue(json, POJO.class);
Run Code Online (Sandbox Code Playgroud)

但是避免将数据实际序列化为JSON,而是使用内存中的事件序列作为中间步骤.

  • 对于新读者来说,请注意:代码片段中的 TypeReference 类来自“com.fasterxml.jackson.core.type.TypeReference” (3认同)

小智 8

我有类似的问题,其中我们有包含值列表的 GenericResponse 对象

 ResponseEntity<ResponseDTO> responseEntity = restTemplate.exchange(
                redisMatchedDriverUrl,
                HttpMethod.POST,
                requestEntity,
                ResponseDTO.class
        );
Run Code Online (Sandbox Code Playgroud)

使用 objectMapper 有助于将 LinkedHashMap 转换为相应的 DTO 对象

 ObjectMapper mapper = new ObjectMapper();

 List<DriverLocationDTO> driverlocationsList = mapper.convertValue(responseDTO.getData(), new TypeReference<List<DriverLocationDTO>>() { });
Run Code Online (Sandbox Code Playgroud)