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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With