Scala - 如何从 Avro 模式中获取所有字段名称?
Scala - How to get all the fields name from an Avro schema?
我有一个 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 执行相同的操作?
val myAvroSchemaText= io.Source.fromInputStream(getClass.getResourceAsStream("pair.avsc")).mkString
val avroSchema = new Schema.Parser().parse(myAvroSchemaText)
avroSchema.getFields().foreach {
f =>
println(f.name)
}
import collection.JavaConverters._
avroSchema.getFields.asScala.map(_.name())) //forEach
我有一个 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 执行相同的操作?
val myAvroSchemaText= io.Source.fromInputStream(getClass.getResourceAsStream("pair.avsc")).mkString
val avroSchema = new Schema.Parser().parse(myAvroSchemaText)
avroSchema.getFields().foreach {
f =>
println(f.name)
}
import collection.JavaConverters._
avroSchema.getFields.asScala.map(_.name())) //forEach