-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathJsonSerde.java
37 lines (29 loc) · 990 Bytes
/
JsonSerde.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.github.programmingwithmati.model;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serializer;
public class JsonSerde<T> implements Serde<T> {
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final Class<T> type;
public JsonSerde(Class<T> type) {
this.type = type;
}
@Override
public Serializer<T> serializer() {
return (topic, data) -> serialize(data);
}
@SneakyThrows
private byte[] serialize(T data) {
return OBJECT_MAPPER.writeValueAsBytes(data);
}
@Override
public Deserializer<T> deserializer() {
return (topic, bytes) -> deserialize(bytes);
}
@SneakyThrows
private T deserialize(byte[] bytes) {
return OBJECT_MAPPER.readValue(bytes, type);
}
}