我有一个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]


但是我希望它只返回数组列表中的“ left”和“ right”,而不返回其他任何内容。现在,它也返回类型和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);
      }
  }

关于java - 如何从Avro Schema获取所有字段名称?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40758224/

10-16 05:42