golang中json和struct的使用说明
在struct的字段后面加入json:'key'可以进行json格式输出,其中key为json的键名
type SuccessResponse struct { Code int `json:'code'` Msg string `json:'msg'` Data interface{} `json:'data'`}func SuccessRsp(ctx *gin.Context, data interface{}) { res := SuccessResponse{ Code: 0, Msg: 'success', Data: data, } ctx.JSON(http.StatusOK, res)}type MyData struct { Id int `json:'id'` Name string `json:'name'`}func ListAllOncallPlan(ctx *gin.Context) { //你的业务代码 //...... data = Mydata{Id:1, Name:'zhangsan'} SuccessRsp(ctx, plans)}响应的结果为:{ 'code': 0, 'msg': 'ok', 'data': { 'id': 1, 'name': 'zhangsan' }}tips:
1.如果struct的某个字段没有传值,则输出的json为默认值,可以通过'omitempty'参数忽略掉值为空的键
type MyData struct { Id int `json:'id,omitempty'` Name string `json:'name'`}data = Mydata{Name:'zhangsan'}SuccessRsp(ctx, plans)
则id的键会被忽略掉,输出json为:
{ 'code': 0, 'msg': 'ok', 'data': { 'name': 'zhangsan' }}
2.可以用'-'来完全掉忽略掉某个键, 比如下面的id不会被转化到json字段中
type MyData struct { Id int `json:'-'` Name string `json:'name'`}2、将数据库的字段转化成struct
如果使用gorm框架进行数据库连接,则可以用gorm:'column:key'来指定数据库的键,如下所示
type User struct { Id int64 `gorm:'column:id' json:'id'` Namestring `gorm:'column:name' json:'name,omitempty'`}
补充:golang 一键生成 form,json,gorm标签
每次有新表产生时,就会有新的model,model编写完后,繁杂的标签注解令人烦躁,所以写了这样的工具。
func AddJsonFormGormTag(in string) (string) {var result stringscanner := bufio.NewScanner(strings.NewReader(in))var oldLineTmp = ''var lineTmp = ''var propertyTmp = ''var seperateArr []stringfor scanner.Scan() {oldLineTmp = scanner.Text()lineTmp = strings.Trim(scanner.Text(), ' ')if strings.Contains(lineTmp, '{') || strings.Contains(lineTmp, '}') {result = result + oldLineTmp + 'n'continue}seperateArr = Split(lineTmp, ' ')// 接口或者父类声明不参与tag, 自带tag不参与tagif len(seperateArr) == 1 || len(seperateArr) == 3 {continue}propertyTmp = HumpToUnderLine(seperateArr[0])oldLineTmp = oldLineTmp + fmt.Sprintf(' `gorm:'column:%s' json:'%s' form:'%s'`', propertyTmp, propertyTmp, propertyTmp)result = result + oldLineTmp + 'n'}return result}// 增强型split,对 a,,,,,,,b,,c 以','进行切割成[a,b,c]func Split(s string, sub string) []string {var rs = make([]string, 0, 20)tmp := ''Split2(s, sub, &tmp, &rs)return rs}// 附属于Split,可独立使用func Split2(s string, sub string, tmp *string, rs *[]string) {s = strings.Trim(s, sub)if !strings.Contains(s, sub) {*tmp = s*rs = append(*rs, *tmp)return}for i, _ := range s {if string(s[i]) == sub {*tmp = s[:i]*rs = append(*rs, *tmp)s = s[i+1:]Split2(s, sub, tmp, rs)return}}}// 驼峰转下划线func HumpToUnderLine(s string) string{if s =='ID' {return 'id'}var rs stringelements:=FindUpperElement(s)for _,e :=range elements{s =strings.Replace(s, e, '_'+strings.ToLower(e),-1)}rs = strings.Trim(s,' ')rs = strings.Trim(rs,'t')return strings.Trim(rs,'_')}// 找到字符串中大写字母的列表,附属于HumpToUnderLinefunc FindUpperElement(s string) []string {var rs = make([]string, 0, 10)for i := range s {if s[i] >= 65 && s[i] <= 90 {rs = append(rs, string(s[i]))}}return rs}如何使用
func TestAddJsonFormTag(t *testing.T) { rs := AddJsonFormGormTag(` type User struct{ Iduint64 NameSpace string DailyRoutine int } `) fmt.Println(rs)}结果
type User struct{ Iduint64 `gorm:'column:id' json:'id' form:'id'` NameSpace string `gorm:'column:name_space' json:'name_space' form:'name_space'` DailyRoutine int `gorm:'column:daily_routine' json:'daily_routine' form:'daily_routine'` }
具体对齐,使用go fmt xxx.go 命令
goland 快捷键是 ctrl alt L
以上为个人经验,希望能给大家一个参考,也希望大家多多支持好吧啦网。如有错误或未考虑完全的地方,望不吝赐教。
相关文章: