在AVRO模式中,如果需要定义一个带有默认的对象数组的字段,可以使用default
关键字。以下是一个示例:
{
"type": "record",
"name": "MyRecord",
"fields": [
{
"name": "name",
"type": "string"
},
{
"name": "friends",
"type": {
"type": "array",
"items": {
"type": "record",
"name": "Friend",
"fields": [
{
"name": "name",
"type": "string"
},
{
"name": "age",
"type": "int"
}
]
}
},
"default": []
}
]
}
在上面的示例中,定义了一个名为MyRecord
的AVRO记录类型。该记录类型包含两个字段:name
和friends
。name
字段是一个字符串类型,而friends
字段是一个对象数组类型。对象数组的每个元素都是一个名为Friend
的记录类型,包含name
和age
字段。
在friends
字段上使用了default
关键字,并将其设置为一个空数组[]
。这意味着如果没有提供friends
字段的值,将使用默认的空数组。
使用AVRO工具生成代码时,可以根据上面的模式生成相应的类,以便在代码中使用。例如,使用AVRO工具生成的Java类可以如下所示:
public class MyRecord {
private String name;
private List friends;
// getters and setters
public static class Friend {
private String name;
private int age;
// getters and setters
}
}
通过使用上述代码和模式,可以创建一个MyRecord
对象,并设置name
和friends
字段的值。如果没有提供friends
字段的值,将使用默认的空数组。
MyRecord record = new MyRecord();
record.setName("John");
record.setFriends(new ArrayList<>()); // 使用空数组作为默认值
// 添加朋友到数组中
List friends = record.getFriends();
friends.add(new MyRecord.Friend("Alice", 25));
friends.add(new MyRecord.Friend("Bob", 30));
注意:代码示例中的Java类是根据模式生成的,你可以根据自己使用的编程语言和工具进行相应的修改。