Created
November 25, 2023 18:20
-
-
Save GithubUser5462/3a5ffff89f0f79d8dd289e79b1ffc086 to your computer and use it in GitHub Desktop.
Golang: Generate an error when a JSON field is present but the corresponding struct field is missing - Disallow Unknown Fields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"encoding/json" | |
"fmt" | |
) | |
type User struct { | |
Name string `json:"name"` | |
Age int `json:"age"` | |
} | |
func main() { | |
jsonString := `{"name": "John Doe", "age": 30, "location": "New York"}` | |
var user User | |
dec := json.NewDecoder(bytes.NewReader([]byte(jsonString))) | |
dec.DisallowUnknownFields() | |
err := dec.Decode(&user) | |
if err != nil { | |
fmt.Println("err:", "Decode:", err) | |
} | |
fmt.Printf("%+v\n", user) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment