json

最后更新于:2022-04-02 02:43:33

[TOC] ## 标识符 ### omitempty 为空不显示 添加`omitempty`后,如果 data 为空,则不显示 data 如 0 ,"",flase 等都为空值 ``` type H struct{ Msg string `json:"msg"` Data interface{} `json:"data,omitempty"` } ``` `{"name":"asd"}` ### - 过滤都该字段的序列化 ``` type H struct{ Msg string `json:"msg"` Data interface{} `json:"-"` } ``` `{"name":"asd"}` ### 指定序列化格式,可让 int 转为 string ``` type User struct { Name string `json:"name"` Age int8 `json:"age,string"` } ``` `{"name":"asd","age":"123"}` ## json.Marshal ``` type ColorGroup struct { ID int Name string Colors []string } group := ColorGroup{ ID: 1, Name: "Reds", Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, } b, err := json.Marshal(group) if err != nil { fmt.Println("error:", err) } fmt.Printf("%+v\n", string(b)) // {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]} ``` ## json.Unmarshal ``` var jsonBlob = []byte(`[ {"Name": "Platypus", "Order": "Monotremata"}, {"Name": "Quoll", "Order": "Dasyuromorphia"} ]`) type Animal struct { Name string Order string } var animals []Animal err := json.Unmarshal(jsonBlob, &animals) if err != nil { fmt.Println("error:", err) } fmt.Printf("%+v", animals) // [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}] ``` ### json.Indent 缩进json ``` var jsonBlob = []byte(`[ {"Name": "Platypus", "Order": "Monotremata"}, {"Name": "Quoll", "Order": "Dasyuromorphia"} ]`) var a bytes.Buffer err := json.Indent(&a, jsonBlob, "", " ") if err != nil { panic(err) } fmt.Printf("%+v\n", a.String()) /* [ { "Name": "Platypus", "Order": "Monotremata" }, { "Name": "Quoll", "Order": "Dasyuromorphia" } ] */ ``` ## json.HTMLEscape ``` var out bytes.Buffer json.HTMLEscape(&out, []byte(`{"Name":"HTML content"}`)) out.WriteTo(os.Stdout) // Output: //{"Name":"\u003cb\u003eHTML content\u003c/b\u003e"} ``` ## json.NewDecoder 有杂质信息也可序列化 ``` type User struct { UserName string `json:"username"` Password string `json:"password"` } jsonString := `{ "username": "foobar@example.com", "password": "YOUR PASSWORD" }otherinfo` str := strings.NewReader(jsonString) // io.Reader usr := User{} err := json.NewDecoder(str).Decode(&usr) if err != nil { log.Fatalf("Decode failed, %#v\n", err) } log.Printf("User %#v\n", usr)//User main.User{UserName:"foobar@example.com", Password:"YOUR PASSWORD"} ```
';