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 lo
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();
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.