問題描述
如何序列化/反序列化使用 ScalaPB 的“oneof”的 protobuf 消息? (How to serialize/deserialize a protobuf message that uses 'oneof' with ScalaPB?)
我正在使用 ScalaPB 編譯我的 Scala 案例類以序列化我的 protobuf 消息。
我有一個包含以下消息的 .proto
文件:
message WrapperMessage {
oneof msg {
Login login = 1;
Register register = 2;
}
}
message Login {
required string email = 1;
required string password = 2;
}
message Register {
required string email = 1;
required string password = 2;
optional string firstName = 3;
optional string lastName = 4;
}
如果知道我想將 Login
消息放入 msg
中,如何創建我的 WrapperMessage
?
val login = Login(email = "test@example.com", password = "testpass")
val wrapperMessage = WrapperMessage(???)
val wrapperMessageBytes = wrapperMessage.toByteArray
現在假設我正在通過網絡接收 WrapperMessage
;如何使用 ScalaPB 案例類方法反序列化消息?
參考解法
方法 1:
ScalaPB has documentation which clearly provides examples for the questions I am asking. In this answer I tailor the examples provided on ScalaPB towards my question.
To initialize a message with oneof
:
val login = Login(email = "test@example.com", password = "testpass")
val wrapperMessage = WrapperMessage().withLogin(login)
To match against a message's oneof
field:
wrapperMessage.msg match {
case Msg.Login(l) => // handle l
case Msg.Register(r) => // handle r
case Msg.Empty => // handle exceptional case...
}
方法 2:
You should be able to initialize WrapperMessage
with an empty constructor and call .set_login(login)
You would deserialize to WrapperMessage
and pattern match on message.WhichOneof
which returns either "login" or "register". Then you would call the accessor on that specific message (ie. message.login
).
(by Edward Maxedon、Edward Maxedon、kliew)