简体   繁体   English

java中的Avro到json转换器

[英]Avro to json converter in java

I am reading Avro from kafka as a string and I am trying to convert the String avro to Json using java code.我正在从 kafka 读取 Avro 作为字符串,我正在尝试使用 java 代码将字符串 avro 转换为 Json。

    @KafkaListener(topics = "#{'${kafka.consumer.topics}'.split(',')}", containerFactory = "kafkaListenerContainerFactory")
    void listener(String message, Acknowledgment acknowledgment, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) throws CacheServiceException, JsonProcessingException {

//some code here
byte[] data = message.getBytes(); //This seems to be the issue

avroToJson(schema,data)


}

//Code to convert avro to json
public String avroToJson(Schema schema, byte[] avroBinary) throws IOException {
        DatumReader<Object> datumReader = new GenericDatumReader<>(schema);
        Decoder decoder = DecoderFactory.get().binaryDecoder(avroBinary, null);
        Object avroDatum = datumReader.read(null, decoder);
        System.out.println("Initiating loop");
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            DatumWriter<Object> writer = new GenericDatumWriter<>(schema);
            JsonEncoder encoder = EncoderFactory.get().jsonEncoder(schema, baos, false);
            writer.write(avroDatum, encoder);
            encoder.flush();
            baos.flush();
            return new String(baos.toByteArray(), StandardCharsets.UTF_8);
        }
    }

I want to avoid reading data as AVRO from kafka as I am reading data from different topics with different Schemas in same kafka.我想避免从 kafka 读取数据作为 AVRO,因为我正在从同一个 kafka 中使用不同模式的不同主题读取数据。

Avro is used to validate your data against the schema. Avro 用于根据架构验证您的数据。 if you don't want this, simply remove Avro and use only Kafka.如果您不想要这个,只需删除 Avro 并仅使用 Kafka。 From the producer, side send json data instead of avro serialized data.从生产者那里发送 json 数据而不是 avro 序列化数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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