1.omitempty 如果对应的字段没有值,则忽略,有,则不会略
2.- 永久忽略
代码:
package mainimport ("encoding/json""fmt" )type Person struct {Name string `json:"name"`Age int `json:"age"`Addr string `json:"addr,omitempty"` //不存在,则忽略.存在则,不忽略 } type Animal struct {Name string `json:"name"`Sex string `json:"sex"`Color string `json:"-"` //永久忽略 }type Alien struct {Name string `json:"name"`Sex string `json:"sex"`Height string `json:"height"` }func main() {p1 := Person{Name: "code",Age: 30,Addr: "北京",}data, err := json.Marshal(p1)if err != nil {fmt.Println(err)}fmt.Printf("%s\n", data)a1:=Animal{Name: "花花",Sex: "女",Color: "黄色",}data, err = json.Marshal(a1)if err != nil {fmt.Println(err)}fmt.Printf("%s\n", data)a2:=Alien{Name: "smart",Sex: "没有性别",Height: "20m",}data, err = json.Marshal(a2)if err != nil {fmt.Println(err)}fmt.Printf("%s\n", data) }