Golang Decoding Generic JSON Objects to One of Many Formats

拈花ヽ惹草 提交于 2019-11-28 08:49:22

One way to handle this is to define a struct for the fixed part of the message with a json.RawMessage field to capture the variant part of the message. Decode the json.RawMessage to a type specific to the variant:

type Message struct {
  Type      string `json:type`
  Timestamp string `json:timestamp`
  Data      json.RawMessage
}  

type Event struct {
   Type    string `json:type`
   Creator string `json:creator`
}


var m Message
if err := json.Unmarshal(data, &m); err != nil {
    log.Fatal(err)
}
switch m.Type {
case "event":
    var e Event
    if err := json.Unmarshal([]byte(m.Data), &e); err != nil {
        log.Fatal(err)
    }
    fmt.Println(m.Type, e.Type, e.Creator)
default:
    log.Fatal("bad message type")
}

playground example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!