Decoding generic JSON objects to one of many formats

前端 未结 1 564
广开言路
广开言路 2020-12-05 17:03

I am working on a general JSON based message passing protocol in Go. What I would like to do is have a BaseMessage that has general information like Type<

相关标签:
1条回答
  • 2020-12-05 17:23

    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

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