io.quarkus.kafka.client.serialization.JsonbSerializer Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of quarkus-kafka-client Show documentation
Show all versions of quarkus-kafka-client Show documentation
Connect to Apache Kafka with its native API
package io.quarkus.kafka.client.serialization;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import jakarta.json.bind.Jsonb;
import org.apache.kafka.common.serialization.Serializer;
/**
* A {@link Serializer} that serializes to JSON using JSON-B.
*/
public class JsonbSerializer implements Serializer {
public static final String NULL_AS_NULL_CONFIG = "json.serialize.null-as-null";
private final Jsonb jsonb;
private final boolean jsonbNeedsClosing;
private boolean nullAsNull = false;
public JsonbSerializer() {
this(JsonbProducer.get(), true);
}
public JsonbSerializer(Jsonb jsonb) {
this(jsonb, false);
}
private JsonbSerializer(Jsonb jsonb, boolean jsonbNeedsClosing) {
this.jsonb = jsonb;
this.jsonbNeedsClosing = jsonbNeedsClosing;
}
@Override
public void configure(Map configs, boolean isKey) {
if (configs.containsKey(NULL_AS_NULL_CONFIG) && Boolean.parseBoolean((String) configs.get(NULL_AS_NULL_CONFIG))) {
nullAsNull = true;
}
}
@Override
public byte[] serialize(String topic, T data) {
if (nullAsNull && data == null) {
return null;
}
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
jsonb.toJson(data, output);
return output.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void close() {
if (!jsonbNeedsClosing) {
return;
}
try {
jsonb.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy