如何序列化/反序列化使用 'oneof' 和 ScalaPB 的 protobuf 消息? [英] How to serialize/deserialize a protobuf message that uses 'oneof' with ScalaPB?
问题描述
我正在使用 ScalaPB 编译我的 Scala 案例类以序列化我的 protobuf 消息.
I'm using ScalaPB to compile my Scala case classes for serializing my protobuf messages.
我有一个带有以下消息的 .proto
文件:
I have a .proto
file with the following messages:
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;
}
如何创建我的 WrapperMessage
知道我想把 Login
消息放在 msg
中?
How do I create my WrapperMessage
knowing that I want to put a Login
message inside the msg
?
val login = Login(email = "test@example.com", password = "testpass")
val wrapperMessage = WrapperMessage(???)
val wrapperMessageBytes = wrapperMessage.toByteArray
现在假设我通过线路接收到 WrapperMessage
;如何使用 ScalaPB 案例类方法反序列化消息?
Let's say now that I am receiving a WrapperMessage
over the wire; how do I deserialize the message using ScalaPB case class methods?
推荐答案
ScalaPB 的文档清楚地为我提出的问题提供了示例.在这个答案中,我针对我的问题量身定制了 ScalaPB 上提供的示例.
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.
使用 oneof
初始化消息:
val login = Login(email = "test@example.com", password = "testpass")
val wrapperMessage = WrapperMessage().withLogin(login)
匹配消息的 oneof
字段:
wrapperMessage.msg match {
case Msg.Login(l) => // handle l
case Msg.Register(r) => // handle r
case Msg.Empty => // handle exceptional case...
}
这篇关于如何序列化/反序列化使用 'oneof' 和 ScalaPB 的 protobuf 消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!