You can achieve that with Jackson (ObjectMapper).
// Raw data.
String data = "type: x, code: y, time: 25";
// Mapper raw data to map.
Map<String, String> map = Arrays.asList(data.split(","))
.stream()
.map(s -> s.split(":"))
.collect(Collectors
.toMap(
s -> s[0].trim(),
s -> s[1].trim()));
// Jackson's ObjectMapper.
final ObjectMapper objectMapper = new ObjectMapper();
final MyDTO myDTO = objectMapper.convertValue(map, MyDTO.class);
- Split entry pairs and convert string array to
List<String> in order to use java.lang.Collection.Stream API from Java 1.8,
- Map the resulting string list
key:value to a string array with [0] as key and [1] as value,
- Use
.collect(..) terminal method from stream API to mutate,
- Use the
Collectors.toMap() static method which take two function to perform mutation from input type to key and value type,
- All that's left is to convert the
Map to DTO with the ObjectMapper.
If there is a value in the raw data that is not in the DTO, see here to ignore it!