How to unmarshal JSON into interface{} in Go?

前端 未结 1 1851
醉酒成梦
醉酒成梦 2020-12-05 10:03

I\'m a newbie in Go and now I have a problem. I have a type called Message, it is a struct like this:

type Message struct {
    Cmd string `json:\"cmd\"`
            


        
相关标签:
1条回答
  • 2020-12-05 10:32

    Define a struct type for the fixed part of the message with a json.RawMessage field to capture the variant part of the message. Define struct types for each of the variant types and decode to them based on the the command.

    type Message struct {
      Cmd string `json:"cmd"`
      Data      json.RawMessage
    }  
    
    type CreateMessage struct {
        Conf map[string]int `json:"conf"`
        Info map[string]int `json:"info"`
    }  
    
    func main() {
        var m Message
        if err := json.Unmarshal(data, &m); err != nil {
            log.Fatal(err)
        }
        switch m.Cmd {
        case "create":
            var cm CreateMessage
            if err := json.Unmarshal([]byte(m.Data), &cm); err != nil {
                log.Fatal(err)
            }
            fmt.Println(m.Cmd, cm.Conf, cm.Info)
        default:
            log.Fatal("bad command")
        }
    }
    

    playground example

    0 讨论(0)
提交回复
热议问题