简体   繁体   中英

How to encode a java POJO as json so that it is avro compatible?

I need to serialize an object to Json, but the format should be avro compatible.

By that I mean, if the object has an optional field, it should be written as "fieldName": { "fieldType": "fieldValue" }

Is there any class in apache avro that can do that?

My avro schema looks like this:

{
  "type": "record",
  "name": "TrialAssignments",
  "namespace": "com.ferozed.experimentation",
  "fields": [
    {
      "name": "key",
      "type": [
        "null",
        "string"
      ],
      "doc": "key used to generate trial/treatments *",
      "default": null
    }
   ]
}

A valid Avro compatible json representation of this would be:

{
   "key": { "string": "value" }
}

But if I use a generic Json encoder like com.google.gson or Jackson it produces:

{
    "key": "value"
}

which is not the correct avro encoding for the schema.

Try checking this resource https://karengryg.io/2018/08/25/avro-and-pojo-conversionstips-for-kafka-devs/

private static <T> GenericRecord pojoToRecord(T model) throws IOException {
        Schema schema = ReflectData.get().getSchema(model.getClass());

        ReflectDatumWriter<T> datumWriter = new ReflectDatumWriter<>(schema);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(outputStream, null);
        datumWriter.write(model, encoder);
        encoder.flush();

        DatumReader<GenericRecord> datumReader = new GenericDatumReader<>(schema);
        BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(outputStream.toByteArray(), null);

        return datumReader.read(null, decoder);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM