2016-11-23 93 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包含? –

相关问题