代码之家  ›  专栏  ›  技术社区  ›  user9750148

Scala-如何从Avro模式中获取所有字段的名称?

  •  0
  • user9750148  · 技术社区  · 6 年前

    我有一个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进行同样的操作?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Belwal    5 年前
    import collection.JavaConverters._
    avroSchema.getFields.asScala.map(_.name())) //forEach
    
        2
  •  0
  •   ameet chaubal    6 年前
    val myAvroSchemaText= io.Source.fromInputStream(getClass.getResourceAsStream("pair.avsc")).mkString
    val avroSchema = new Schema.Parser().parse(myAvroSchemaText)
    
    avroSchema.getFields().foreach {
      f =>
        println(f.name)
    }