This question already has an answer here:
With golang script, I have a struct type and json below
struct
admin
type Admin struct {
Id string `json:"id"`
Status int `json:"status"`
}
json
jsonData
{
"id": "uuid"
}
When I using json.Unmarshal(jsonData, &admin)
with jsonData above does not have status
value
Default value of admin.Status
is 0
. How i can check admin.Status
is not set?
Thanks so much!
</div>
Use a pointer for Status
field:
package main
import (
"fmt"
"encoding/json"
)
type Admin struct {
Id string `json:"id"`
Status *int `json:"status"`
}
func main() {
b := []byte(`{"id": 1}`)
r := new(Admin)
json.Unmarshal(b, r)
fmt.Println(r.Status)
b2 := []byte(`{"id": 1, "status": 2}`)
r2 := new(Admin)
json.Unmarshal(b2, r2)
fmt.Println(*r2.Status)
}
When its not present in Json, the pointer would be nil.