使用 json 编码/解码时,有没有办法序列化自定义结构?
假设您有 3 个(在我的实际代码中有 10 个)不同的自定义结构,它们通过 udp 发送,并且您使用 json 进行编码:
type a struct {
Id int
Data msgInfo
}
type b struct {
Id int
Data msgInfo
Other metaInfo
}
type c struct {
Other metaInfo
}
在接收端,您想知道接收到的结构体是 a、b 或 c 类型,因此它可以例如传递到类型特定的通道。
type msgtype reflect.Type
.
.
nrOfBytes, err := udpConn.Read(recievedBytes)
if err != nil {...}
var msg interface{}
err = json.Unmarshal(recievedBytes[0:nrOfBytes], &msg)
if err != nil {...}
u := reflect.ValueOf(msg)
msgType := u.Type()
fmt.Printf("msg is of type: %s\n", msgType)
使用 gob,这很容易通过注册类型来完成,但我必须使用 json,因为它是通过 udp 进行通信的,所以无论如何要序列化自定义结构?我想要打印
msg is of type: a
但我只是得到
msg is of type: map[string]interface {}
RISEBY
潇潇雨雨
相关分类