protobuf.js version: 6.6.5
When encoding a plain object representing a message with a oneof field, the field containing the value will be ignored will be ignored unless there is an additional object member with which is the name of the oneof field mapping to the string name of the field chosen. But that additional object member is not required when using fromObject, or emitted by toObject.
In addition, in ProtoBuf.js 5, that additional object member was always emitted by the toObject equivalent, and that was very convenient for use in switch statements. My preferred solution here would be to always emit that field member in toObject.
// oneof.proto
syntax = "proto3";
message OneOfMessage {
oneof choice {
int32 first = 1;
string second = 2;
}
}
var protobuf = require('protobufjs');
protobuf.load('oneof.proto', function(err, root) {
if (err) {
throw err;
}
var OneOfMessage = root.lookup('OneOfMessage');
var value1 = {choice: 'first', first: 5};
console.log('value1:', value1);
var buffer1 = OneOfMessage.encode(value1).finish();
var value1_decoded = OneOfMessage.decode(buffer1).toObject();
// {first: 5}
console.log('value1_decoded:', value1_decoded);
var value2 = {first: 5};
console.log('value2:', value2);
var buffer2 = OneOfMessage.encode(value2).finish();
var value2_decoded = OneOfMessage.decode(buffer2).toObject();
// {}
console.log('value2_decoded:', value2_decoded);
var value3 = {first: 5};
console.log('value3:', value3);
var message3 = OneOfMessage.fromObject(value3);
var value3_decoded = message3.toObject();
// {first: 5}
console.log('value3_decoded:', value3_decoded);
});
I think the most important thing to note is that encoding and decoding value1 twice gives a different result than doing so just once.
protobuf.js version: 6.6.5
When encoding a plain object representing a message with a
oneoffield, the field containing the value will be ignored will be ignored unless there is an additional object member with which is the name of theoneoffield mapping to the string name of the field chosen. But that additional object member is not required when usingfromObject, or emitted bytoObject.In addition, in ProtoBuf.js 5, that additional object member was always emitted by the
toObjectequivalent, and that was very convenient for use inswitchstatements. My preferred solution here would be to always emit that field member intoObject.I think the most important thing to note is that encoding and decoding
value1twice gives a different result than doing so just once.