原问题地址:validate-struct field if it exists
有定义结构
go
package main
import (
"fmt"
"encoding/json"
)
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")
}
反射方式
go
import (
"log"
"reflect"
)
func main() {
type test struct {
A bool
B bool
C bool
}
v := new(test)
metaValue := reflect.ValueOf(v).Elem()
for _, name := range []string{"A", "C", "Z"} {
field := metaValue.FieldByName(name)
if field == (reflect.Value{}) {
log.Printf("Field %s not exist in struct", name)
}
}
}
借助 json 库
go
package main
import (
"fmt"
"encoding/json"
)
func main() {
fmt.Println("Hello, World!")
type Meta struct{
FcTag struct{
Name string `json:"name"`
Value json.Number `json:"value"`
} `json:"fc_tag"`
}
template := `{"fc_tag": {"name": "tiger"}}`
var meta1 Meta
err := json.Unmarshal([]byte(template), &meta1)
if err != nil {
fmt.Println("err=", err.Error())
}else{
fmt.Printf("meta1=%#v\n", meta1.FcTag.Value)
}
template = `{"fc_tag": {"name": "tiger", "value": 1}}`
var meta2 Meta
err2 := json.Unmarshal([]byte(template), &meta2)
if err2 != nil {
fmt.Println("err=", err2.Error())
}else{
fmt.Printf("meta2=%#v\n", meta2.FcTag.Value)
}
}
/*
Hello, World!
meta1=""
meta2="1"
*/
给以后解决类似问题,提供了不错的思路👍🏻