json tag妙用

Posted by JC on December 2, 2020

最近在迭代的时候遇到json的两个问题,解决方法都是通过tag来解决的。记录一下。

  1. beego的orm映射,如果结构体的字段和数据库里的不一样,或者列名带id的可能会冲突,会重新建一列,要通过orm的tag来指定列名:
type NetworkConfig struct {
	NetConfID uint64 `json:"net_conf_id" orm:"pk;column(net_conf_id);"`

	K8sConfig  string `json:"k8s_conf" orm:"column(k8s_conf)"`
	NetConfig  string `json:"net_conf" orm:"column(net_conf)"`
	NodeConfig string `json:"node_conf" orm:"column(node_conf)"`

	ConfType ConfigType `json:"conf_type"`

	UpdatedAt int64 `json:"updated_at"`
	CreatedAt int64 `json:"created_at"`
	DeletedAt int64 `json:"-"`

	NetID uint64 `json:"-" orm:"column(net_id)"`

  1. 业务里有个把前端界面的内容打包成json的string传给后端,但是前端json里有的uint64的字段传的是string类型,在后期unmarshal的时候发现类型不匹配的报错,通过tag指定原始数据类型来解决:
    type NetConf struct {
     ...
    
     BatchTimeout      uint32 `json:"batch_timeout,string"`
     MaxMessageCount   uint32 `json:"max_message_count,string"`
     AbsoluteMaxBytes  uint32 `json:"absolute_max_bytes,string"`
     PreferredMaxBytes uint32 `json:"preferred_max_bytes,string"`
    
     ...
    }
    

例如想把string字段解析到uint32的字段的结构体里,会报错,指定tag标明原始类型,可以正常把string类型的值解析到相应的字段里。

另外也可以通过json.Number类型,调用该类型的string,int和float方法转换。