如何用Java(Spring)向Kafka Topic发送JSON格式消息?
Hey there! Let's break down your three questions about sending that specific JSON message to a Kafka topic one by one:
1. How to convert the given JSON to a string?
You’ve got two practical options here:
Directly write the escaped string
In Java, double quotes inside a string literal need to be escaped with backslashes. Your JSON would look like this as a string:String jsonStr = "{\"targetFileInfo\":{\"path\":\"2018-05-07-10/row01-small-01.txt.ready\"}}";Serialize a Java object to JSON string (recommended for dynamic data)
First, create a POJO that matches your JSON structure:public class TargetFileInfo { private String path; // Getters and setters public String getPath() { return path; } public void setPath(String path) { this.path = path; } } public class KafkaMessage { private TargetFileInfo targetFileInfo; // Getters and setters public TargetFileInfo getTargetFileInfo() { return targetFileInfo; } public void setTargetFileInfo(TargetFileInfo targetFileInfo) { this.targetFileInfo = targetFileInfo; } }Then use a JSON library like Jackson or Gson to convert the object to a string. For example, with Jackson:
ObjectMapper objectMapper = new ObjectMapper(); KafkaMessage message = new KafkaMessage(); TargetFileInfo fileInfo = new TargetFileInfo(); fileInfo.setPath("2018-05-07-10/row01-small-01.txt.ready"); message.setTargetFileInfo(fileInfo); String jsonStr = objectMapper.writeValueAsString(message);
2. Maven dependencies for JSON serialization (similar to JSON.stringify)
Java doesn’t have a built-in JSON.stringify function, so you’ll need a third-party library. Here are the most common options with their Maven dependencies:
Jackson (industry standard)
Add this to your pom.xml:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> <!-- Use the latest stable version available --> </dependency>
Gson (Google’s lightweight library)
Add this to your pom.xml:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> <!-- Use the latest stable version available --> </dependency>
With Gson, serialization is just as simple:
Gson gson = new Gson(); String jsonStr = gson.toJson(message);
3. Can I send the message directly without converting it to a string?
It depends on your Kafka setup:
Native Kafka Producer (default configuration)
The defaultStringSerializerexpects a string input, so you can’t send the JSON object directly. You’ll either need to convert it to a string (as we covered) or serialize it to a byte array manually and use theByteArraySerializer.Using a framework or custom serializer
If you’re using a framework like Spring Kafka, you can configure aJsonSerializerto handle conversion automatically. This lets you send the Java object directly— the serializer will turn it into a JSON-formatted byte stream behind the scenes.For example, in Spring Kafka, set up your producer factory like this:
@Bean public ProducerFactory<String, KafkaMessage> producerFactory() { Map<String, Object> configProps = new HashMap<>(); // Add your Kafka broker connection configs here configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); return new DefaultKafkaProducerFactory<>(configProps); }Then you can send the
KafkaMessageobject directly viaKafkaTemplatewithout manual string conversion.
内容的提问来源于stack exchange,提问作者guguli

