Issue
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.
Solution
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 usejava.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
toDTO
with theObjectMapper
.
If there is a value in the raw data that is not in the DTO
, see here to ignore it!
Answered By - İsmail Y.
Answer Checked By - Katrina (JavaFixing Volunteer)