Google Protocol Buffers:如何在proto文件中定义ArrayList<ArrayList<String>>消息
如何在Protobuf中定义嵌套的字符串列表(对应ArrayList<ArrayList>)
好问题!在Protocol Buffers里,并没有直接支持repeated repeated string这种嵌套重复字段的写法,要实现类似ArrayList<ArrayList<String>>的结构,我们需要借助嵌套消息来完成。
具体步骤很简单:
- 先定义一个内层消息,用来承载单个的字符串列表(对应外层列表里的每个
ArrayList<String>) - 在主消息中,用
repeated修饰这个内层消息类型,就能得到嵌套的列表结构
下面是完整的示例代码:
// 内层消息:用来封装一组字符串,对应单个ArrayList<String> message StringList { repeated string items = 1; } // 主消息:包含嵌套的字符串列表,对应ArrayList<ArrayList<String>> message m1 { repeated StringList nested_mylist = 1; }
补充说明
Protobuf的设计规则里,repeated只能修饰基本类型或消息类型,不能直接嵌套使用repeated。通过把内层的字符串列表封装成独立消息,就能完美实现多层嵌套的列表结构。
在生成的Java代码中,nested_mylist对应的类型就是List<StringList>,而每个StringList的items字段是List<String>,正好对应你需要的ArrayList<ArrayList<String>>(Protobuf默认的列表实现就是ArrayList)。
你可以根据业务场景调整消息和字段的命名,只要保证同一个消息内的字段号唯一即可。
内容的提问来源于stack exchange,提问作者Feihua Fang
相关产品推荐
相关产品推荐

