gpt4 book ai didi

java - 如何从 Avro Schema 获取所有字段名称?

转载 作者:行者123 更新时间:2023-11-30 07:58:04 24 4
gpt4 key购买 nike

我有一个 avro 模式,我想从中提取所有字段名称。有什么办法吗?

测试模式是这样的:

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

代码如下:

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

上面打印出来的是这样的:

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

但我希望它只返回数组列表中的“左”和“右”,而不返回其他任何内容。现在它也返回我不需要的 type 和 pos。有什么办法可以得到吗?

最佳答案

您可以使用 field.name() 来做到这一点,如下所示:

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

关于java - 如何从 Avro Schema 获取所有字段名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40758224/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com