0
我有一個Avro的模式是這樣的 -如何在解碼原始字節數組後更改特定的字段值?
{
"type":"record",
"name":"new_user",
"namespace":"com.hello",
"fields":[
{
"name":"user_id",
"type":[
"long",
"null"
]
},
{
"name":"segment",
"type":[
"string",
"null"
]
}
]
}
我用我上面的Avro架構這樣的序列化數據,並且給了我一個字節數組,並工作正常 -
public static void main(String[] args) throws IOException {
Schema schema = new Parser()
.parse("{ \"type\":\"record\", \"name\":\"new_user\", \"namespace\":\"com.hello\", \"fields\":[ { \"name\":\"user_id\", \"type\":[ \"long\", \"null\" ] }, { \"name\":\"segment\", \"type\":[ \"string\", \"null\" ] } ] }");
byte[] originalAvrodata = getAvroBinaryData(schema);
// how to get newAvroData byte array in which user_id
// is change to some other random long number?
}
private static byte[] getAvroBinaryData(Schema schema) throws IOException {
GenericRecord record = new GenericData.Record(schema);
record.put("user_id", 123456L);
record.put("segment", "hello");
GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<GenericRecord>(schema);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Encoder e = EncoderFactory.get().binaryEncoder(os, null);
writer.write(record, e);
e.flush();
byte[] byteData = os.toByteArray();
return byteData;
}
問題陳述:
我需要將originalAvrodata
字節數組解碼,然後將user_id
字段值改變爲其它一些long
編號然後構造一個newAvroData
字節數組使用相同的模式應該有user_id
字段值到一些隨機long
數字。這有可能通過任何使用Avro的機會來實現嗎?