[英]protobufjs encode a wrapper message which includes an inner field with type google.protobuf.Any
I am using protobufjs library in Nodejs to send a message to a kafka topic and read the message from a java consumer.我在 Nodejs 中使用 protobufjs 库向 kafka 主题发送消息并从 java 消费者读取消息。
Following are the protobuf definition.以下是 protobuf 定义。 The Inner message should be packed in the Wrapper message field. Inner 消息应该打包在 Wrapper 消息字段中。
message Wrapper {
google.protobuf.Any message = 1;
}
message Inner {
string field1 = 1;
}
I used the following three methods to encode the message but when deserializing i get error "Type of the Any message does not match the given class."我使用以下三种方法对消息进行编码,但在反序列化时出现错误“任何消息的类型与给定的 class 不匹配。” in the java consumer.在 java 消费者中。
const rootWrapper = await protobuf.load('wrapper.proto');
const Wrapper = rootWrapper.lookupType('Wrapper');
const rootInner = await protobuf.load('inner.proto');
const Inner = rootInner.lookupType('Inner');
const rootAnyProto = await protobuf.load('node_modules/google-proto-files/google/protobuf/any.proto');
const Any = rootAnyProto.lookupType('google.protobuf.Any');
Method 1方法一
const innerMsg = { field1 : 'value1'}
const wrapper = { message: innerMsg }
const encodedWrapper = Wrapper.encode(wrapper).finish()
Method 2方法二
const innerMsg = { field1 : 'value1'}
const innerMsgEncoded = Inner.encode(innerMsg).finish()
const wrapper = { message: innerMsgEncoded }
const encodedWrapper = Wrapper.encode(wrapper).finish()
Method 3方法三
const innerMsg = { field1 : 'value1'}
const innerMsgEncoded = Any.encode(innerMsg).finish()
const wrapper = { message: innerMsgEncoded }
const encodedWrapper = Wrapper.encode(wrapper).finish()
Anyone can help on the correct way to encode an protobuf message with an inner message?任何人都可以帮助以正确的方式使用内部消息对 protobuf 消息进行编码?
After many tries i resolved my issue in the following manner.经过多次尝试,我通过以下方式解决了我的问题。
const innerMsg = { field1 : 'value1'}
const innerMsgEncoded = Any.encode(innerMsg).finish()
const any = Any.create({ type_url : 'type.googleapis.com/Inner', value : innerMsgEncoded });
const wrapper = { message: any}
const encodedWrapper = Wrapper.encode(wrapper).finish()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.