Creating objects from Primitive avro schema

332 Views Asked by At

Suppose I have a schema in avro like this

{ "type" : "string" }

How should i create object from this schema in java?

1

There are 1 best solutions below

0
On

I did not found a way to do it directly with the java avro lib

but you can still do this

  public static byte[] jsonToAvro(String json, Schema schema) throws IOException {
    DatumReader<Object> reader = new GenericDatumReader<>(schema);
    GenericDatumWriter<Object> writer = new GenericDatumWriter<>(schema);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    Decoder decoder = DecoderFactory.get().jsonDecoder(schema, json);
    Encoder encoder = EncoderFactory.get().binaryEncoder(output, null);
    Object datum = reader.read(null, decoder);
    writer.write(datum, encoder);
    encoder.flush();
    return output.toByteArray();
  }
Schema PRIMITIVE = new Schema.Parser().parse("{ \"type\" : \"string\" }");
byte[] b = jsonToAvro("\"" + mystring + "\"", PRIMITIVE);

from How to avro binary encode my json string to a byte array?