Through a Rest API endpoint, I accept JSON and using a Kafka Producer, I publish the JSON to a topic. The JSON will have this format:
{
"id": "uniqueIdentifier",
"name": "PersonName",
"age": PersonAge
}
and the send message method in my Kafka Producer looks like this:
public void sendMessage(Person p){
LOGGER.info(String.format("Message sent -> %s", p.toString()));
Message<Person> message = MessageBuilder
.withPayload(p)
.setHeader(KafkaHeaders.TOPIC, "jsonTopic")
.build();
kafkaTemplate.send(message);
}
I need to check if the JSON has all the fields non-empty and if the age > 0
.
How would I need to implement the verification before sending the message?
2
Answers
JSON Schema is the best for this use case. There are libraries in all languages to validate an input JSON against JSON-Schema. E.g. Java, Javascript
The schema for your requirement should look like the following:
Here,
additionalProperties
ensures that you do not allow anything else apart from the declared properties.These validation libraries give very detailed validation errors that make the error actionable for the sender/caller:
For the Person POJO I would suggest the member variables to have
@NotNull
– to ensure the value for each member variable is provided.Use
@Min(1)
to have a value more than 0 for age.When declaring the method do as
public void sendMessage(@Valid Person p)
to ensure validation is done on invoking the method.On error handling do the following:
Above can be thrown incase any condition above is thrown. But it needs to be caught using an advice as below:
Above will give you appropriate message for the malformed payload.