How to parse JSON in golang without unmarshaling twice

前端 未结 3 1408
甜味超标
甜味超标 2021-01-06 17:16

I\'ve got a web socket connection that sends different types of messages in a JSON object, and I want to unmarshal the contents into some known structs. To do this, I figur

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-06 17:40

    You will want to create a struct which contains all keys you might receive, then unmarshal once, finally based on which keys are nil you can decide what kind of packet you got.

    The example below displays this behavior: https://play.golang.org/p/aFG6M0SPJs

    package main
    
    import (
      "encoding/json"
      "fmt"
      "strings"
    )
    
    
    type Ack struct {
      Messages []string `json:"messages"`
    }
    
    type Packet struct {
      Ack  * Ack    `json:"ack"`
      Ping * string `json:"ping"`
    }
    
    func runTest(testJSON []byte) {
      var p = Packet{}
      err := json.Unmarshal(testJSON, &p)
      if err != nil {
        fmt.Println("error unmarshalling: ", err)
      }
      if (p.Ack != nil) {
        fmt.Println("Got ACK: ", strings.Join(p.Ack.Messages, ", "));
      } else if (p.Ping != nil){
              fmt.Println("Got PING");
      }
    }
    
    func main() {
      tests := [][]byte{
        []byte(`{"ack":{"messages":["Hi there","Hi again"]}}`),
        []byte(`{"ping": "Are you there?"}`),
      }
      for _, test := range tests {
        runTest(test)
      }
    
    }
    

提交回复
热议问题