skip to Main Content

I have an Avro Schema (org.apache.avro.Schema) and a data object. I want to serialize the object into a JSON string according to the schema. Is there any way to do that?

Thanks in advance!

2

Answers


  1. Chosen as BEST ANSWER

    I found a way to get the fields in the Avro schema and use them as a filter for custom serializer. See https://www.baeldung.com/jackson-serialize-field-custom-criteria


  2. You can use a JsonEncoder:

    public String serialiseToJson(MyAvroType value) {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final Encoder jsonEncoder = EncoderFactory.get().jsonEncoder(MyAvroType.getClassSchema(), baos);
        final DatumWriter<MyAvroType> writer = new SpecificDatumWriter<>(MyAvroType.class);
    
        writer.write(value, jsonEncoder);
        jsonEncoder.flush();
    
        return new String(baos.toByteArray());
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search