Home > database >  Parse String line and store into DTO
Parse String line and store into DTO

Time:10-02

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.

CodePudding user response:

You'll need to write some custom logic.

Try this.

(Assuming, type & code are char & time is int)

String s = "type: x, code: y, time: 25";
final String[] parts = s.split(",");
DTO dto = new DTO();
for (final String part : parts) {
     final String[] keyValue = part.trim().split(":");
     final String key = keyValue[0].trim();
     final String value = keyValue[1].trim();
     if ("type".equals(key)) {
          dto.setType(value.charAt(0));
     } else if ("code".equals(key)) {
          dto.setCode(value.charAt(0));
     } else if ("time".equals(key)) {
          dto.setTime(Integer.parseInt(value));
     }
}

CodePudding user response:

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);
  1. Split entry pairs and convert string array to List<String> in order to use java.lang.Collection.Stream API from Java 1.8,
  2. Map the resulting string list key:value to a string array with [0] as key and [1] as value,
  3. Use .collect(..) terminal method from stream API to mutate,
  4. Use the Collectors.toMap() static method which take two function to perform mutation from input type to key and value type,
  5. 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!

  • Related