去 websocket 序列化/反序列化 json [英] Go websocket serialization/deserialization json
问题描述
我正在使用 gorilla websocket,我正在计划使用 json 进行序列化/反序列化.
I'm using gorilla websocket, and i'm planing using json for serialization/deserialization.
假设我有这样的结构来接收传入的消息:
Let say i have struct like this for receive the incoming messages:
type Foo struct {
A string `json:"a"`
B string `json:"b"`
}
和
type Bar struct {
C string `json:"c"`
D string `json:"d"`
}
gorilla 提供 conn.ReadJSON
用于接收传入的消息.传入的消息可以是 Foo 或 Bar,但我不能使用 conn.ReadJSON(Foo)
并侦听其他 conn.ReadJSON(Bar)
,这是一团糟.我想要一些类似于 conn.ReadJSON(Messages)
的东西,比如 javascript 中的 JSON.parse()
.如果收到 Foo,如何处理传入消息,然后将其存储到 Foo
结构中,如果收到 Bar,则将其存储到 Bar
结构中?
gorilla provide conn.ReadJSON
for receive incoming messages. The incoming messages can be Foo or Bar but i can't use conn.ReadJSON(Foo)
and listen for other conn.ReadJSON(Bar)
, it's a mess. I want something like just conn.ReadJSON(Messages)
, like JSON.parse()
in javascript. How to handle incoming messages if Foo is received, then it stored into Foo
struct, and if Bar is received then it stored into Bar
struct ?
我认为解决方案是使用这个结构:
I'm thingking the solution is using this struct:
type Messages struct {
Control string `json:"control"`
X // Data type for either Foo or Bar struct
}
传入的消息现在有 json 控件,控件的值可以是 Foo 或 Bar.使用 if else
if control==Foo then X
赋值给 Foo,else X
赋值给 Bar.但我无法计算 X
的数据类型.
The incoming messages now have json control, value of control can be Foo or Bar. Using if else
if control==Foo then X
is assign to Foo, else X
is assign to Bar. But i can't figured the data type for X
.
欢迎任何解决方案,谢谢.
Any sollution is welcome, thankyou.
推荐答案
使用 RawMessage.
type Messages struct {
Control string `json:"control"`
X json.RawMessage
}
var m Messages
err := c.ReadJSON(&m)
if err != nil {
// handle error
}
switch m.Control {
case "Foo":
var foo Foo
if err := json.Unmarshal([]byte(m.X), &foo); err != nil {
// handle error
}
// do something with foo
case "Bar":
... follow pattern for Foo
}
这篇关于去 websocket 序列化/反序列化 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!