简体   繁体   中英

Generating Json String from Avro Schema and Data Object

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!

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());
}

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

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