【问题标题】:Creating objects from Primitive avro schema从原始 avro 模式创建对象
【发布时间】:2018-08-22 12:47:55
【问题描述】:

假设我在 avro 中有这样的架构

{ "type" : "string" }

我应该如何在 java 中从这个模式创建对象?

【问题讨论】:

    标签: java avro spark-avro jackson-dataformat-avro


    【解决方案1】:

    我没有找到直接使用 java avro lib 的方法

    但你仍然可以这样做

      public static byte[] jsonToAvro(String json, Schema schema) throws IOException {
        DatumReader<Object> reader = new GenericDatumReader<>(schema);
        GenericDatumWriter<Object> writer = new GenericDatumWriter<>(schema);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        Decoder decoder = DecoderFactory.get().jsonDecoder(schema, json);
        Encoder encoder = EncoderFactory.get().binaryEncoder(output, null);
        Object datum = reader.read(null, decoder);
        writer.write(datum, encoder);
        encoder.flush();
        return output.toByteArray();
      }
    Schema PRIMITIVE = new Schema.Parser().parse("{ \"type\" : \"string\" }");
    byte[] b = jsonToAvro("\"" + mystring + "\"", PRIMITIVE);
    

    来自How to avro binary encode my json string to a byte array?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-09
      • 2019-02-09
      • 1970-01-01
      • 2012-07-27
      • 1970-01-01
      • 2021-10-04
      • 2022-07-18
      相关资源
      最近更新 更多