2016-11-23 98 views
1

我有一個avro模式,我想從中提取所有的字段名稱。有沒有辦法做到這一點?如何從Avro Schema獲取所有字段名稱?

測試模式是這樣的:

{ 
    "type": "record", 
    "name": "wpmcn.MyPair", 
    "doc": "A pair of strings", 
    "fields": [ 
     {"name": "left", "type": "string"}, 
     {"name": "right", "type": "string"} 
    ] 
} 

下面是代碼:

public static void main(String[] args) throws IOException { 
    Schema schema = 
     new Schema.Parser().parse(AvroTest.class.getClassLoader().getResourceAsStream("pair.avsc")); 
    System.out.println(schema.getFields()); 
    } 

上面打印出這樣的:

[left type:STRING pos:0, right type:STRING pos:1] 

但我想,這應該只是回報數組列表中的「左」和「右」,沒有別的。現在它返回類型和pos以及我不需要的。有什麼辦法可以得到嗎?

回答

2

你可以通過使用field.name(),如下圖所示:

public static void main(String[] args) throws IOException { 
    Schema schema = 
     new Schema.Parser().parse(AvroTest.class.getClassLoader(). 
      getResourceAsStream("pair.avsc")); 

    //Collect all field values to an array list 
    List<String> fieldValues = new ArrayList<>(); 
    for(Field field : schema.getFields()) { 
      fieldValues.add(field.name()); 
     } 

     //Iterate the arraylist 
     for(String value: fieldValues) { 
      System.out.println(value); 
     } 
    } 
+0

什麼AvroTest包含? –

相關問題