转到websocket序列化/反序列化json [英] Go websocket serialization/deserialization json
问题描述
我正在使用大猩猩网络套接字,并且我打算使用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"`
}
大猩猩提供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.如果控制== Foo,则使用if else
,然后将X
分配给Foo,否则将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屋!