Validate struct field if it exists

后端 未结 1 1815
春和景丽
春和景丽 2021-02-14 17:54

I\'m POSTing a JSON user object to my Golang application where I decode the \'req.body\' into a \'User\' struct.

err := json.NewDecoder(req.Body).Decode(user)
//         


        
1条回答
  •  失恋的感觉
    2021-02-14 18:39

    You can use a pointer to a string:

    type User struct {
        Name     string  `json:"name,omitempty"`
        Username *string `json:"username,omitempty"`
        Email    string  `json:"email,omitempty"`
        Town     string  `json:"town,omitempty"`
        //more fields here
    }
    
    func main() {
        var u, u2 User
        json.Unmarshal([]byte(`{"username":"hi"}`), &u)
        fmt.Println("username set:", u.Username != nil, *u.Username)
        json.Unmarshal([]byte(`{}`), &u2)
        fmt.Println("username set:", u2.Username != nil)
        fmt.Println("Hello, playground")
    }
    

    playground

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