【问题标题】:Convert JSON string to Avro GenericRecord in Java (the generated Schema is through the same Json string)在Java中将JSON字符串转换为Avro GenericRecord(生成的Schema是通过相同的Json字符串)
【发布时间】:2020-04-18 23:53:10
【问题描述】:

我将 JSON 字符串作为输入, 我使用这个将 Json 字符串转换为 avro 模式

架构模式 = JsonUtil.inferSchema(JsonUtil.parse(jsonString), “模式”);

我有可以在模式注册表中注册的 avro 模式。

我需要一个来自同一字符串的通用记录,因为 JSON 数据也包含这些值。

【问题讨论】:

  • 你从哪里得到这个 JsonUtil 类?请出示
  • @cricket_007 我是从 Kitesdk.data 得到的

标签: json apache-kafka avro confluent-schema-registry


【解决方案1】:

听起来您正在尝试以编程方式重新创建 kafka-avro-console-producer,它将架构作为 CLI 参数,然后将 JSON 匹配架构作为用户输入。

你可以在那里找到对应的jsonToAvro方法

https://github.com/confluentinc/schema-registry/blob/master/avro-serializer/src/main/java/io/confluent/kafka/formatter/AvroMessageReader.java

仅使用 Avro 包含的 JSONDecoder

  private Object jsonToAvro(String jsonString, Schema schema) {
    try {
      DatumReader<Object> reader = new GenericDatumReader<Object>(schema);
      Object object = reader.read(null, decoderFactory.jsonDecoder(schema, jsonString));

      if (schema.getType().equals(Schema.Type.STRING)) {
        object = ((Utf8) object).toString();
      }
      return object;
    } catch (IOException e) {
      throw new SerializationException(
          String.format("Error deserializing json %s to Avro of schema %s", jsonString, schema), e);
    } catch (AvroRuntimeException e) {
      throw new SerializationException(
          String.format("Error deserializing json %s to Avro of schema %s", jsonString, schema), e);
    }
  }

这将返回一个字符串或一个 GenericRecord 实例

【讨论】:

    【解决方案2】:

    我用过

    tech.allegro.schema.json2avro.converter
    

    现在我需要传递架构和 json 数据(作为字节),这会给我记录。

    JsonAvroConverter avroConverter = new JsonAvroConverter();
    
    GenericData.Record record =
    avroConverter.convertToGenericDataRecord(json.getBytes(), avroSchema);
    

    【讨论】:

    • AFAICT,这只是我复制的代码的包装。无需在 Avro 之外添加另一个依赖项
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 2023-04-01
    相关资源
    最近更新 更多