Partly JSON unmarshal into a map in Go

前端 未结 3 1827
一向
一向 2020-11-29 15:34

My websocket server will receive and unmarshal JSON data. This data will always be wrapped in an object with key/value pairs. The key-string will act as value identifier, te

3条回答
  •  一生所求
    2020-11-29 16:32

    Here is an elegant way to do similar thing. But why do partly JSON unmarshal? That doesn't make sense.

    1. Create your structs for the Chat.
    2. Decode json to the Struct.
    3. Now you can access everything in Struct/Object easily.

    Look below at the working code. Copy and paste it.

    import (
       "bytes"
       "encoding/json" // Encoding and Decoding Package
       "fmt"
     )
    
    var messeging = `{
    "say":"Hello",
    "sendMsg":{
        "user":"ANisus",
        "msg":"Trying to send a message"
       }
    }`
    
    type SendMsg struct {
       User string `json:"user"`
       Msg  string `json:"msg"`
    }
    
     type Chat struct {
       Say     string   `json:"say"`
       SendMsg *SendMsg `json:"sendMsg"`
    }
    
    func main() {
      /** Clean way to solve Json Decoding in Go */
      /** Excellent solution */
    
       var chat Chat
       r := bytes.NewReader([]byte(messeging))
       chatErr := json.NewDecoder(r).Decode(&chat)
       errHandler(chatErr)
       fmt.Println(chat.Say)
       fmt.Println(chat.SendMsg.User)
       fmt.Println(chat.SendMsg.Msg)
    
    }
    
     func errHandler(err error) {
       if err != nil {
         fmt.Println(err)
         return
       }
     }
    

    Go playground

提交回复
热议问题