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

1)如果我们要使用 schema1 验证上面的 json,它应该说 true

2)如果我们要使用schema2验证上面的json,它应该说false,因为“age”字段根据模式是int,但在json中它是字符串

public static boolean validateJson(byte[] data, Schema schema) throws Exception {
    InputStream input = new ByteArrayInputStream(data);
    DataInputStream din = new DataInputStream(input);
    GenericDatumReader<Object> reader = null;
    Object datum = null;
    BinaryDecoder binaryDecoder =
            DecoderFactory.get().binaryDecoder(input, null);
    try {
        reader = new GenericDatumReader<Object>(schema);
        DatumWriter<Object> writer = new GenericDatumWriter<Object>(schema);
        Decoder decoder = DecoderFactory.get().binaryDecoder(input, null);
        reader.read(din, decoder);
        return true;
    } catch (AvroTypeException e) {
        System.out.println(e.getMessage());
        return false;
    }
}

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

0 回答 0