[java] Casting LinkedHashMap to Complex Object

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;

Where SomeObject might look like this:

private int anInteger;
private SomeOtherObject;

and SomeOtherObject might look like this:

private long aLong;
private float aFloat; 

This is fine an the object gets marshalled no problem and stored in the DB as a JSON string.

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.

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.

If I do this:

for (LinkedHashMap lhm : someObjectList) {
    // Convert the values back
}

I get a compile error telling me that someObjectList is of type 'SomeObject' not LinkedHashMap.

If I do this:

for (SomeObject lhm : someObjectList) {
    // Convert the values back
}

I get a runtime error telling me that LinkedHashMap cannot be cast to 'SomeObject'.

This question is related to java casting jackson linkedhashmap

The answer is


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>>() { });

this is functionally same as if you did:

byte[] json = mapper.writeValueAsBytes(singleObject);
POJO pojo = mapper.readValue(json, POJO.class);

but avoids actual serialization of data as JSON, instead using an in-memory event sequence as the intermediate step.


I had similar Issue where we have GenericResponse object containing list of values

 ResponseEntity<ResponseDTO> responseEntity = restTemplate.exchange(
                redisMatchedDriverUrl,
                HttpMethod.POST,
                requestEntity,
                ResponseDTO.class
        );

Usage of objectMapper helped in converting LinkedHashMap into respective DTO objects

 ObjectMapper mapper = new ObjectMapper();

 List<DriverLocationDTO> driverlocationsList = mapper.convertValue(responseDTO.getData(), new TypeReference<List<DriverLocationDTO>>() { });

There is a good solution to this issue:

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper objectMapper = new ObjectMapper();

***DTO premierDriverInfoDTO = objectMapper.convertValue(jsonString, ***DTO.class); 

Map<String, String> map = objectMapper.convertValue(jsonString, Map.class);

Why did this issue occur? I guess you didn't specify the specific type when converting a string to the object, which is a class with a generic type, such as, User <T>.

Maybe there is another way to solve it, using Gson instead of ObjectMapper. (or see here Deserializing Generic Types with GSON)

Gson gson = new GsonBuilder().create();

Type type = new TypeToken<BaseResponseDTO<List<PaymentSummaryDTO>>>(){}.getType();

BaseResponseDTO<List<PaymentSummaryDTO>> results = gson.fromJson(jsonString, type);

BigDecimal revenue = results.getResult().get(0).getRevenue();

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to casting

Subtracting 1 day from a timestamp date Cast object to interface in TypeScript TypeScript enum to object array Casting a number to a string in TypeScript Hive cast string to date dd-MM-yyyy Casting int to bool in C/C++ Swift double to string No function matches the given name and argument types C convert floating point to int PostgreSQL : cast string to date DD/MM/YYYY

Examples related to jackson

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to convert JSON string into List of Java object? Deserialize Java 8 LocalDateTime with JacksonMapper java.lang.IllegalArgumentException: No converter found for return value of type java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value How to modify JsonNode in Java? Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error Convert Map to JSON using Jackson Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter

Examples related to linkedhashmap

Casting LinkedHashMap to Complex Object How to iterate through LinkedHashMap with lists as values java collections - keyset() vs entrySet() in map Java LinkedHashMap get first or last entry