我有一个示例Avro架构:
{
"type": "record",
"name": "wpmcn.MyPair",
"doc": "A pair of strings",
"fields": [
{"name": "left", "type": "string"},
{"name": "right", "type": "string"}
]
}
在Java中,这将是一种获取所有字段名称的方法:
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);
}
}
如何使用Scala执行相同操作?
答案 0 :(得分:1)
import collection.JavaConverters._
avroSchema.getFields.asScala.map(_.name())) //forEach
答案 1 :(得分:0)
val myAvroSchemaText= io.Source.fromInputStream(getClass.getResourceAsStream("pair.avsc")).mkString
val avroSchema = new Schema.Parser().parse(myAvroSchemaText)
avroSchema.getFields().foreach {
f =>
println(f.name)
}