This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
package main
/**
Tag是结构体的元信息,可以在运行的时候通过反射的机制读取出来。 Tag在结构体字段的后方定义,由一对反引号包裹起来,具体的格式如下:
`key1:"value1" key2:"value2"`
*/
import (
"encoding/json"
"fmt"
)
// Student2 学生
type Student2 struct {
ID int `json:"id"` //通过指定tag实现json序列化该字段时的key
Gender string //json序列化是默认使用字段名作为key
name string //私有不能被json包访问
}
func main() {
s1 := Student2{
ID: 1,
Gender: "男",
name: "沙河娜扎",
data, err := json.Marshal(s1)
if err != nil {
fmt.Println("json marshal failed!")
return
fmt.Printf("json str:%s\n", data) //json str:{"id":1,"Gender":"男"}