Avro operates at the record level associated with the circuit. I donβt think there is such a concept as "convert this JSON fragment to bytes for the Avro field regardless of any schema or record."
Assuming the array is part of a larger JSON record, if you start with a write string, you can do
public static byte[] jsonToAvro(String json, String schemaStr) throws IOException { InputStream input = null; DataFileWriter<GenericRecord> writer = null; Encoder encoder = null; ByteArrayOutputStream output = null; try { Schema schema = new Schema.Parser().parse(schemaStr); DatumReader<GenericRecord> reader = new GenericDatumReader<GenericRecord>(schema); input = new ByteArrayInputStream(json.getBytes()); output = new ByteArrayOutputStream(); DataInputStream din = new DataInputStream(input); writer = new DataFileWriter<GenericRecord>(new GenericDatumWriter<GenericRecord>()); writer.create(schema, output); Decoder decoder = DecoderFactory.get().jsonDecoder(schema, din); GenericRecord datum; while (true) { try { datum = reader.read(null, decoder); } catch (EOFException eofe) { break; } writer.append(datum); } writer.flush(); return output.toByteArray(); } finally { try { input.close(); } catch (Exception e) { } } }
source share