How do I Unmarshal JSON?

前端 未结 3 867
难免孤独
难免孤独 2020-12-16 06:21

I am still learning Go. I am trying to unmarshal a json into a struct. However, the struct has a field with a tag. Using reflection, I try to see if the tag has the string \

3条回答
  •  忘掉有多难
    2020-12-16 07:00

    The problem here is that you are using one encoding format for two protocols and probably there is something wrong in your model.

    That is a valid Json payload and should be handled as such. One trick that you can use is to create another field to handle the "string" json and one to handle the "json struct". See this modified example: I first unmarshal json and then marshal back to json to create the final string to upload to the database. One field is used for unmarshaling and the other to communicate with the DB.

    package main
    
    import(
    "fmt"
    "encoding/json"
    )
    
    
    const data = `{"i":3, "S":{"phone": {"sales": "2223334444"}}}`
    type A struct {
        I int64
        Sjson struct {
           Phone struct {
              Sales string `json:"sales"`
           } `json:"phone"`
        } `json:"S", sql:"-"`
        S string `sql:"type:json",json:"-"`
    }
    
    func main() {
        msg := A{}
        _ = json.Unmarshal([]byte(data), &msg)
        data, _ := json.Marshal(msg.Sjson)
        msg.S = string(data)
        fmt.Println("Done", msg)
    }
    

提交回复
热议问题