I receive a String line through Kafka that looks like that:
type: x, code: y, time: 25
is it possible to map this String to a java DTO? I only dealt with JSON string before and used object mapper to convert JSON to DTO but never a one line String. I have a DTO class that has type, code and time as fields.
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);
List<String>
in order to use java.lang.Collection.Stream
API from Java 1.8,key:value
to a string array with [0]
as key and [1]
as value,.collect(..)
terminal method from stream API to mutate,Collectors.toMap()
static method which take two function to perform mutation from input type to key and value type,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!