如何从 Avro Schema 获取所有字段名称?

How to get all the fields name from Avro Schema?

我有一个 avro 架构,我想从中提取所有字段名称。有什么办法吗?

测试模式是这样的:

{
    "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]

但我希望它应该只是 return "left" 和 "right" 在一个数组列表中,没有别的。现在它 returns 类型和 pos 以及我不需要的。有什么办法可以得到吗?

您可以使用 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);
      }
  }
 Schema.getClassSchema().getFields()

>= Java 8

schema.getFields().forEach(System.out::println)// print
schema.getFields().stream().map(Schema.Field::name) // collect