java - 如何将我的 json 字符串进行 avro 二进制编码为字节数组?

标签 java json bytearray avro

我有一个实际的 JSON 字符串,我需要将其 avro 二进制编码为字节数组。经过Apache Avro specification ,我想出了下面的代码。

我不确定这样做是否正确。谁能看看我尝试对 JSON 字符串进行 avro 二进制编码的方式是否正确?我使用的是 Apache Avro 1.7.7 版本。

public class AvroTest {

    private static final String json = "{" + "\"name\":\"Frank\"," + "\"age\":47" + "}";
    private static final String schema = "{ \"type\":\"record\", \"namespace\":\"foo\", \"name\":\"Person\", \"fields\":[ { \"name\":\"name\", \"type\":\"string\" }, { \"name\":\"age\", \"type\":\"int\" } ] }";

    public static void main(String[] args) throws IOException {
        byte[] data = jsonToAvro(json, schema);

        String jsonString = avroToJson(data, schema);
        System.out.println(jsonString);
    }

    /**
     * Convert JSON to avro binary array.
     * 
     * @param json
     * @param schemaStr
     * @return
     * @throws IOException
     */
    public static byte[] jsonToAvro(String json, String schemaStr) throws IOException {
        InputStream input = null;
        GenericDatumWriter<Object> writer = null;
        Encoder encoder = null;
        ByteArrayOutputStream output = null;
        try {
            Schema schema = new Schema.Parser().parse(schemaStr);
            DatumReader<Object> reader = new GenericDatumReader<Object>(schema);
            input = new ByteArrayInputStream(json.getBytes());
            output = new ByteArrayOutputStream();
            DataInputStream din = new DataInputStream(input);
            writer = new GenericDatumWriter<Object>(schema);
            Decoder decoder = DecoderFactory.get().jsonDecoder(schema, din);
            encoder = EncoderFactory.get().binaryEncoder(output, null);
            Object datum;
            while (true) {
                try {
                    datum = reader.read(null, decoder);
                } catch (EOFException eofe) {
                    break;
                }
                writer.write(datum, encoder);
            }
            encoder.flush();
            return output.toByteArray();
        } finally {
            try {
                input.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * Convert Avro binary byte array back to JSON String.
     * 
     * @param avro
     * @param schemaStr
     * @return
     * @throws IOException
     */
    public static String avroToJson(byte[] avro, String schemaStr) throws IOException {
        boolean pretty = false;
        GenericDatumReader<Object> reader = null;
        JsonEncoder encoder = null;
        ByteArrayOutputStream output = null;
        try {
            Schema schema = new Schema.Parser().parse(schemaStr);
            reader = new GenericDatumReader<Object>(schema);
            InputStream input = new ByteArrayInputStream(avro);
            output = new ByteArrayOutputStream();
            DatumWriter<Object> writer = new GenericDatumWriter<Object>(schema);
            encoder = EncoderFactory.get().jsonEncoder(schema, output, pretty);
            Decoder decoder = DecoderFactory.get().binaryDecoder(input, null);
            Object datum;
            while (true) {
                try {
                    datum = reader.read(null, decoder);
                } catch (EOFException eofe) {
                    break;
                }
                writer.write(datum, encoder);
            }
            encoder.flush();
            output.flush();
            return new String(output.toByteArray());
        } finally {

        }
    }

}

最佳答案

它似乎至少在起作用。但它可以简化:循环是无用的,因为有多个对象会导致无效的 JSON。此外,通过预解析来避免不必要的模式解析可能是个好主意。

这是我的版本:

public class AvroTest {

    private static final String JSON = "{" + "\"name\":\"Frank\"," + "\"age\":47" + "}";
    private static final Schema SCHEMA = new Schema.Parser().parse("{ \"type\":\"record\", \"namespace\":\"foo\", \"name\":\"Person\", \"fields\":[ { \"name\":\"name\", \"type\":\"string\" }, { \"name\":\"age\", \"type\":\"int\" } ] }");

    public static void main(String[] args) throws IOException {
        byte[] data = jsonToAvro(JSON, SCHEMA);

        String jsonString = avroToJson(data, SCHEMA);
        System.out.println(jsonString);
    }

    /**
     * Convert JSON to avro binary array.
     * 
     * @param json
     * @param schema
     * @return
     * @throws IOException
     */
    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();
    }

    /**
     * Convert Avro binary byte array back to JSON String.
     * 
     * @param avro
     * @param schema
     * @return
     * @throws IOException
     */
    public static String avroToJson(byte[] avro, Schema schema) throws IOException {
        boolean pretty = false;
        GenericDatumReader<Object> reader = new GenericDatumReader<>(schema);
        DatumWriter<Object> writer = new GenericDatumWriter<>(schema);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        JsonEncoder encoder = EncoderFactory.get().jsonEncoder(schema, output, pretty);
        Decoder decoder = DecoderFactory.get().binaryDecoder(avro, null);
        Object datum = reader.read(null, decoder);
        writer.write(datum, encoder);
        encoder.flush();
        output.flush();
        return new String(output.toByteArray(), "UTF-8");
    }
}

关于java - 如何将我的 json 字符串进行 avro 二进制编码为字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27713583/

相关文章:

go - 将换行符分隔的 JSON blob 的整个文件读取到内存中,并在 golang 中使用最少的转换量解码每个 blob?

Java - 将 int 更改为 ascii

JavaFX - 从其他线程更新标签值

php - 使用 Swift 3 XCode 8 解析 JSON

java - 将 JSON 从 React 传递到 Spring Controller

c++ - 整数环绕?

Java 溢出在计算器上计算与 IDE 结果有不同的结果?

java - 哪种帐户报告工具最适合有时限、动态查询和聚合

json - Grails 3如何将json View 呈现到文件输出而不是http响应流?

c# - 我如何将字符串转换为 unsigned int 32 C# 的 byte[]