截至目前,我正在从avsc
模式文件创建avro消息。使用以下代码片段
static byte[] fromJasonToAvro(String json, String schemastr) throws Exception {
InputStream input = new ByteArrayInputStream(json.getBytes());
DataInputStream din = new DataInputStream(input);
Schema schema = Schema.parse(schemastr);
Decoder decoder = DecoderFactory.get().jsonDecoder(schema, din);
DatumReader<Object> reader = new GenericDatumReader<Object>(schema);
Object datum = reader.read(null, decoder);
GenericDatumWriter<Object> w = new GenericDatumWriter<Object>(schema);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Encoder e = EncoderFactory.get().binaryEncoder(outputStream, null);
w.write(datum, e);
e.flush();
return outputStream.toByteArray();
}
public static void main(String[] args) throws Exception {
StringBuilder sb = new StringBuilder();
StringBuilder jsb = new StringBuilder();
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("RsvpAvroSchema.avsc");
InputStream js = classloader.getResourceAsStream("JsonMessage.dat");
InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
InputStreamReader jisr = new InputStreamReader(js, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
BufferedReader jbr = new BufferedReader(jisr);
br.lines().forEach(line -> sb.append(line));
jbr.lines().forEach(line -> jsb.append(line));
System.out.println(sb);
System.out.println(jsb);
System.out.println(new String(fromJasonToAvro(jsb.toString(), sb.toString()), StandardCharsets.UTF_8));
但我也使用maven插件从avsc
创建了avro类(数据结构(。但现在不知道如何将avro message data structure
的主类与string json
消息一起使用来生成avro消息?
有人能分享一下怎么做吗?
更新:
如何从字符串Json创建Avro对象?在我的项目中已经有avro类可用。
第二次更新
public class AvroInstance {
static DecoderFactory DEFAULT_FACTORY = new DecoderFactory();
static DatumReader<Object> reader = new GenericDatumReader<Object>(RSVP.SCHEMA$);
static Object rsvpOB;
public Object avroInstance(String JsonString) {
try {
rsvpOB = reader.read(null, DEFAULT_FACTORY.jsonDecoder(RSVP.SCHEMA$, JsonString));
} catch (IOException e) {
e.printStackTrace();
}
return rsvpOB;
}
您可以将AVSC文件读取器替换为生成类中存储的静态SCHEMA
字符串,以获得相同的字符串。。。
你也可以使用已经完成的库
- https://github.com/allegro/json-avro-converter
- JSON和它自己的Avro支持之间的Jackson对象映射