doutan2456 2016-04-07 14:23
浏览 155
已采纳

Golang自定义JSON序列化(JSON是否存在等效于gob.register()的东西?)

Is there a way to serialize custom structs when encoding/decoding with json?

say you have 3 (in my actual code there are 10) different custom structs which are being sent over udp, and you use json for encoding:

type a struct {
   Id   int
   Data msgInfo
}

type b struct {
   Id       int
   Data     msgInfo
   Other    metaInfo
}

type c struct {
   Other    metaInfo
}

On the recieving end you want to know if the struct recieved was of type a, b or c, so it can for example be passed to a type spesific channel.

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
", msgType)

With gob this is easily done by registering the types, but i have to use json seeing as it's communication over udp, so is there anyway to serialize the custom structs? I want the print to be

msg is of type: a

but i'm only getting

msg is of type: map[string]interface {}
  • 写回答

2条回答 默认 最新

  • dtpoius74857 2016-04-07 15:01
    关注

    One thing you can do is using the json.RawMessage type and a custom Wrapper type. Then, upon receiving a message, you can do a switch (or use a map of constructors) to get the right struct.

    For example (omitting error checking):

    package main
    
    import (   
        "encoding/json"
        "fmt"  
    )          
    
    type Message struct {
        Type string
        Data json.RawMessage
    }          
    
    func (m Message) Struct() interface{} {
        unmarshaller, found := unmarshallers[m.Type]
        if !found {
            return nil
        }      
        return unmarshaller([]byte(m.Data))
    }          
    
    type Foo struct {
        ID int 
    }          
    
    var unmarshallers = map[string]func([]byte) interface{}{
        "foo": func(raw []byte) interface{} {
            var f Foo
            json.Unmarshal(raw, &f)
            return f
        },     
    }          
    
    func main() {
        var body = []byte(`{"Type":"foo","Data":{"ID":1}}`)
        var msg Message
        json.Unmarshal(body, &msg)
    
        switch s := msg.Struct().(type) {
        case Foo:
            fmt.Println(s)
        }      
    }
    

    See this playground example for a live demo http://play.golang.org/p/7FmQqnWPaE

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置