簡體   English   中英

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 做同樣的事情?

import collection.JavaConverters._
avroSchema.getFields.asScala.map(_.name())) //forEach
val myAvroSchemaText= io.Source.fromInputStream(getClass.getResourceAsStream("pair.avsc")).mkString
val avroSchema = new Schema.Parser().parse(myAvroSchemaText)

avroSchema.getFields().foreach {
  f =>
    println(f.name)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM