2
votes

I have an avro schema and from which I want to extract all the fields name. Is there any way to do that?

Test schema is like that:

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

Here is the code:

  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());
  }

Above prints out like that:

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

But I want that it should just return "left" and "right" in an array list and nothing else. Right now it returns type and pos as well which I don't need. Is there any way to get that?

3

3 Answers

3
votes

You can do that by using field.name() as shown below:

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
votes
 Schema.getClassSchema().getFields()
0
votes

>= Java 8

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