- 先安装easyjson
go get -u github.com/mailru/easyjson/
- 在结构体上加//easyjson:json的注解
type School struct {Name string `json:"name"`Addr string `json:"addr"`
}
type Student struct {Id int `json:"id"`Name string `json:"s_name"`School School `json:"s_chool"`Birthday time.Time `json:"birthday"`
}
- 执行命令生成easyjson文件
easyjson -all student.go
- 使用示例
package mainimport ("studygo/easyjson""time""fmt"
)func main(){s:=easyjson.Student{Id: 11,Name:"qq",School:easyjson.School{Name:"CUMT",Addr:"xz",},Birthday:time.Now(),}bt,err:=s.MarshalJSON() fmt.Println(string(bt),err)json:=`{"id":11,"s_name":"qq","s_chool":{"name":"CUMT","addr":"xz"},"birthday":"2017-08-04T20:58:07.9894603+08:00"}`ss:=easyjson.Student{}ss.UnmarshalJSON([]byte(json)) fmt.Println(ss)
}