2015-04-17 19 views
6

Sto convertendo Json in avro. Ho dati json in JSONArray. Quindi mentre lo convertiamo in array di byte, sto affrontando il problema.Conversione JSON in avro

sotto è il mio codice:

static byte [] fromJsonToAvro(JSONArray json, String schemastr) throws Exception { 

ExcelToJson ejj = new ExcelToJson(); 
List<String> list = new ArrayList<String>(); 


if (json != null) { 
    int len = json.length(); 
    for (int i=0;i<len;i++){ 
     list.add(json.get(i).toString()); 
    } 
} 


InputStream input = new ByteArrayInputStream(list.getBytes()); //json.toString().getBytes() 

DataInputStream din = new DataInputStream(input); 
        . 
        . 
        .//rest of the logic 

Così come posso farlo? Come convertire l'oggetto JsonArray in byte (ad esempio, come utilizzare il metodo getBytes() per gli oggetti JsonArray). Il codice sopra riportato che dà un errore allo list.getBytes() e che dice getBytes() non è pronto per la lista.

risposta

2

Avro funziona a livello di record, associato a uno schema. Non penso che esista un concetto come "convertire questo frammento JSON in byte per un campo Avro indipendente da qualsiasi schema o record".

Supponendo che la matrice è parte di una più grande record di JSON, se si sta iniziando con una serie di record, si potrebbe fare

public static byte[] jsonToAvro(String json, String schemaStr) throws IOException { 
    InputStream input = null; 
    DataFileWriter<GenericRecord> writer = null; 
    Encoder encoder = null; 
    ByteArrayOutputStream output = null; 
    try { 
     Schema schema = new Schema.Parser().parse(schemaStr); 
     DatumReader<GenericRecord> reader = new GenericDatumReader<GenericRecord>(schema); 
     input = new ByteArrayInputStream(json.getBytes()); 
     output = new ByteArrayOutputStream(); 
     DataInputStream din = new DataInputStream(input); 
     writer = new DataFileWriter<GenericRecord>(new GenericDatumWriter<GenericRecord>()); 
     writer.create(schema, output); 
     Decoder decoder = DecoderFactory.get().jsonDecoder(schema, din); 
     GenericRecord datum; 
     while (true) { 
      try { 
       datum = reader.read(null, decoder); 
      } catch (EOFException eofe) { 
       break; 
      } 
      writer.append(datum); 
     } 
     writer.flush(); 
     return output.toByteArray(); 
    } finally { 
     try { input.close(); } catch (Exception e) { } 
    } 
} 
4

Per un JSON on-line al convertitore Avro controllare il seguente URL

http://avro4s-ui.landoop.com

Sta usando la libreria avro4s che offre un molte conversioni incluso json => avro