Created
February 23, 2021 08:54
-
-
Save apoorvmote/045b908b1db3eecf6349842b882bc590 to your computer and use it in GitHub Desktop.
This file contains 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 ( | |
"encoding/json" | |
"fmt" | |
) | |
// OptionalInt is for json unmarshal | |
type OptionalInt struct { | |
Value int | |
isValid bool | |
isSet bool | |
} | |
// User is user props | |
type User struct { | |
Views OptionalInt `json:"views"` | |
} | |
func main() { | |
body1 := `{"views": 5}` | |
body2 := `{"views": null}` | |
body3 := `{"age": 5}` | |
var currentUser1 User | |
if err := json.Unmarshal([]byte(body1), ¤tUser1); err != nil { | |
fmt.Println(err) | |
} | |
fmt.Printf("isSet: %v, isValid: %v, value: %v\n", currentUser1.Views.isSet, currentUser1.Views.isValid, currentUser1.Views.Value) | |
var currentUser2 User | |
if err := json.Unmarshal([]byte(body2), ¤tUser2); err != nil { | |
fmt.Println(err) | |
} | |
fmt.Printf("isSet: %v, isValid: %v, value: %v\n", currentUser2.Views.isSet, currentUser2.Views.isValid, currentUser2.Views.Value) | |
var currentUser3 User | |
if err := json.Unmarshal([]byte(body3), ¤tUser3); err != nil { | |
fmt.Println(err) | |
} | |
fmt.Printf("isSet: %v, isValid: %v, value: %v\n", currentUser3.Views.isSet, currentUser3.Views.isValid, currentUser3.Views.Value) | |
} | |
// UnmarshalJSON is custom unmarshal | |
func (i *OptionalInt) UnmarshalJSON(bytes []byte) error { | |
i.isSet = true | |
if string(bytes) == "null" { | |
i.isValid = false | |
return nil | |
} | |
var value int | |
if err := json.Unmarshal(bytes, &value); err != nil { | |
return err | |
} | |
i.isValid = true | |
i.Value = value | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment