How do I validate JSON against Avro schema
14,285
This is how you can validate it programatically.
import org.apache.avro.AvroTypeException;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import java.io.*;
public class MainClass {
public static void main (String [] args) throws Exception {
Schema schema = new Schema.Parser().parse("{\n" +
" \"type\": \"record\",\n" +
" \"namespace\": \"com.acme\",\n" +
" \"name\": \"Test\",\n" +
" \"fields\": [\n" +
" { \"name\": \"name\", \"type\": \"string\" },\n" +
" { \"name\": \"age\", \"type\": \"int\" },\n" +
" { \"name\": \"sex\", \"type\": \"string\" },\n" +
" { \"name\": \"active\", \"type\": \"boolean\" }\n" +
" ]\n" +
"}");
String json = "{\"name\":\"alex\",\"age\":23,\"sex\":\"M\",\"active\":true}";
System.out.println(validateJson(json, schema));
String invalidJson = "{\"name\":\"alex\",\"age\":23,\"sex\":\"M\"}"; // missing active field
System.out.println(validateJson(invalidJson, schema));
}
public static boolean validateJson(String json, Schema schema) throws Exception {
InputStream input = new ByteArrayInputStream(json.getBytes());
DataInputStream din = new DataInputStream(input);
try {
DatumReader reader = new GenericDatumReader(schema);
Decoder decoder = DecoderFactory.get().jsonDecoder(schema, din);
reader.read(null, decoder);
return true;
} catch (AvroTypeException e) {
System.out.println(e.getMessage());
return false;
}
}
}
Related videos on Youtube
Author by
Bhargava Sharma
Updated on July 03, 2022Comments
-
Bhargava Sharma almost 2 years
I have a JSON response from an API and I would like to validate against an existing Avro schema(strict validation with names and types).
The response is of type
{"name":"alex","age":23,"sex":"M","active":"true"}
The schema has the above types with the data types and I would like to validate the schema and throw an exception in case it fails.(Preferably JAVA).
I have read a solution using the command line but I wanted to do it programmatically.
Thanks in advance
-
Filippo Rossoni about 2 yearsto get better error description you can use the builder with StatusUpdated.newBuilder(obj).build() you get an AvroMissingFieldException with meaningful message