使用Postman向gRPC服务器发送对象数组时构造profile_list遇阻
gRPC ProfileList 构造问题与解决方案
问题描述
我的gRPC消息定义如下:
message ModelRescheduleQuoteRequest { string security_token = 1; optional string attribute_to_solve_for = 2; com.myCompany.grpc.gateway.classes.ListValue profile_list = 3; optional string quote_item_to_model_id = 4; com.myCompany.grpc.gateway.classes.RescheduleQuote reschedule_quote = 5; } message ListValue { repeated google.protobuf.Any values = 1; } message Profile { optional int32 number_of_payments = 1; optional double instalment_amount = 2; optional string instalment_frequency_id = 3; optional double instalment_ratio = 4; com.myCompany.grpc.gateway.classes.Date payment_date = 5; } message Date { optional int32 day = 1; optional int32 month = 2; optional int32 year = 3; }
构造profile_list时遇到两个问题:
- 使用带编码值的格式传递时请求正常,但手动输入编码值不现实:
"profile_list": { "values" : [{ "type_url": "type.googleapis.com/com.MyCompany.grpc.gateway.classes.Profile", "value": "CgYzNjQ2OTEpA" }] },
- 尝试用结构化格式传递时,数据无法被正确解析:
"profile_list": { "values" : [{ "@type": "type.googleapis.com/com.MyCompany.grpc.gateway.classes.Profile", "instalmentAmount": 123.45, "instalmentFrequencyId": 123, "instalmentRatio": 1.0, "numberOfPayments": 1, "paymentDate": { "day": 1, "month": 2, "year": 2026 } }] },
补充提问:如果无法通过友好格式传递对象,是否有办法生成对应的编码字符串?
解决方案
1. 修复结构化格式解析问题
结构化格式失效主要有两个原因,修正后即可正常使用:
- 字段命名不匹配:gRPC默认JSON序列化使用下划线命名(snake_case),你用了驼峰命名(camelCase),需统一改成下划线格式,比如
instalmentAmount改为instalment_amount,paymentDate改为payment_date。 - 字段类型不匹配:
Profile中的instalment_frequency_id是string类型,你之前的示例写了数字123,需改为字符串"123"。
修正后的结构化请求示例:
"profile_list": { "values": [{ "@type": "type.googleapis.com/com.myCompany.grpc.gateway.classes.Profile", "number_of_payments": 1, "instalment_amount": 123.45, "instalment_frequency_id": "123", "instalment_ratio": 1.0, "payment_date": { "day": 1, "month": 2, "year": 2026 } }] }
同时要确保你的gRPC网关(比如gRPC-Gateway)已启用google.protobuf.Any的JSON序列化支持,默认配置通常会包含该功能。
2. 生成编码字符串的方法
如果无法使用结构化格式,可以通过以下方式生成google.protobuf.Any的value字段内容:
- 代码序列化生成:
- 使用
protoc编译你的.proto文件,生成对应开发语言的代码(如Java、Python)。 - 在代码中构造
Profile对象并设置所有字段值。 - 将
Profile对象包装进google.protobuf.Any,调用序列化方法得到二进制数据,再将二进制数据转成Base64字符串,即为value字段需要的编码值。
- 使用
- 工具辅助生成:
使用protobuf JSON转二进制工具,输入符合snake_case格式的Profile JSON数据,先转换为二进制格式,再对二进制数据进行Base64编码,即可得到对应的value字符串。
内容的提问来源于stack exchange,提问作者WendyG
相关产品推荐
相关产品推荐

