我想要二進制編碼我的JSON字符串。下面是我的JSON字符串,我創建了一個簡單的方法來完成轉換,但我不確定我所做的方式是否正確?如何使用Apache Avro Avro二進制編碼JSON字符串?
public static void main(String args[]) throws Exception{
try{
Schema schema = new Parser().parse((TestExample.class.getResourceAsStream("/3233.avsc")));
String json="{"+
" \"location\" : {"+
" \"devices\":["+
" {"+
" \"did\":\"9abd09-439bcd-629a8f\","+
" \"dt\":\"browser\","+
" \"usl\":{"+
" \"pos\":{"+
" \"source\":\"GPS\","+
" \"lat\":90.0,"+
" \"long\":101.0,"+
" \"acc\":100"+
" },"+
" \"addSource\":\"LL\","+
" \"add\":["+
" {"+
" \"val\":\"2123\","+
" \"type\" : \"NUM\""+
" },"+
" {"+
" \"val\":\"Harris ST\","+
" \"type\" : \"ST\""+
" }"+
" ],"+
" \"ei\":{"+
" \"ibm\":true,"+
" \"sr\":10,"+
" \"ienz\":true,"+
" \"enz\":100,"+
" \"enr\":10"+
" },"+
" \"lm\":1390598086120"+
" }"+
" }"+
" ],"+
" \"ver\" : \"1.0\""+
" }"+
"}";
byte[] avroByteArray = fromJsonToAvro(json,schema);
} catch (Exception ex) {
// log an exception
}
下面的方法將其轉換我的JSON字符串Avro的二進制編碼 -
private static byte[] fromJsonToAvro(String json, Schema schema) throws Exception {
InputStream input = new ByteArrayInputStream(json.getBytes());
DataInputStream din = new DataInputStream(input);
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();
}
任何人都可以去看看,讓我知道我想Avro的二進制的方式是否我的JSON字符串是否正確不?
對於它的價值,在[Apache的Avro的規範](http://avro.apache.org/docs/1.7.6/spec.html)。 –
目前尚不清楚將JSON「轉換爲Avro」的含義是否意味着什麼,因爲根據規範,Avro符號僅僅是放置在JSON字符串格式上的一組特定約束。 –
無論如何,Apache似乎都提供了[一組實用程序](http://avro.apache。org/docs/current/api/java/index.html),所以目前還不清楚爲什麼你需要編寫自己的。 –