Hello,
I have a use case to read a GenericRecord from its JSON Avro representation
with strict validations. For example, with an Avro schema of two fields 'id'
and 'name', if the JSON has an undefined field, say 'age', I need to raise a
validation exception.
Could you please recommend a way to achieve this with Avro API?
Following is a test case for the requirement.
@Test(expected = IOException.class)
public void validateUndefinedFields() throws Exception {
Schema schema = new Schema.Parser().parse(
"{\"type\": \"record\","
+ "\"name\": \"Test\","
+ "\"namespace\": \"com.example\","
+ "\"fields\":
[{\"name\":\"id\",\"type\":\"string\"},{\"name\":\"name\",\"type\":\"string\"}]}");
DatumReader<GenericRecord> datumReader = new GenericDatumReader<>(schema);
String json = "{\"id\":\"1\", \"age\":27, \"name\":\"abc\"}"; // 'age' is
undefined in the schema
DecoderFactory decoderFactory = DecoderFactory.get();
Decoder jsonDecoder = decoderFactory.jsonDecoder(schema, json);
// This currently does not fail validations.
// TODO: How to validate there are no undefined fields in the input JSON?
datumReader.read(null, jsonDecoder);
}
Thank you.
CONFIDENTIALITY NOTICE This message and any included attachments are from
Cerner Corporation and are intended only for the addressee. The information
contained in this message is confidential and may constitute inside or
non-public information under international, federal, or state securities laws.
Unauthorized forwarding, printing, copying, distribution, or use of such
information is strictly prohibited and may be unlawful. If you are not the
addressee, please promptly delete this message and notify the sender of the
delivery error by e-mail or you may call Cerner's corporate offices in Kansas
City, Missouri, U.S.A at (+1) (816)221-1024.