json同一字段多类型
  • 问题:在json中同一个字段大部分为int,少量为string类型
  • 解决方案:结构体添加json tag
type Product struct {
	Name      string  `json:"name"`
	ProductID int64   `json:"product_id,omitempty"` // omitempty在序列化的时候忽略0值或者空值
	Number    int     `json:"number,string"`        // 额外支持string类型
	Price     float64 `json:"price,string"`         // 额外支持string类型
	IsOnSale  bool    `json:"is_on_sale,string"`    // 额外支持string类型
}
  • 参考:https://blog.csdn.net/qq_33679504/article/details/100533703
json反序列为时间
  • 问题:
    近期在开发中,发现json中的时间类型"2022-05-19 16:09:51"通过json.Unmarshal反序列化转换为time.Time时报错
  • 解决方案:
    golang使用json自定义time类型,然后自己实现json的MarshalJSON和UnmarshalJSON方法,代码如下
package main

import (
	"encoding/json"
	"fmt"
	"time"
)

func main() {
	// json.Unmarshal
	var p Person
	src := `{"id":5,"birthday":"2022-05-19 16:09:51"}`
	_ = json.Unmarshal([]byte(src), &p)
	fmt.Printf("转换后结构体:%+v\n", p)

	// json.Marshal
	pp := Person{
		Id:       1,
		Birthday: p.Birthday,
	}
	ppStr, _ := json.Marshal(pp)
	fmt.Printf("转换后json:%s\n", ppStr)

}

type Person struct {
	Id       int64 `json:"id"`
	Birthday Time  `json:"birthday"`
}

type Time time.Time

const (
	timeFormat = "2006-01-02 15:04:05"
)

func (t *Time) UnmarshalJSON(data []byte) (err error) {
	if string(data) == "null" {
		return nil
	}
	now, err := time.ParseInLocation(`"`+timeFormat+`"`, string(data), time.Local)
	*t = Time(now)
	return
}

func (t Time) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(timeFormat)+2)
	b = append(b, '"')
	b = time.Time(t).AppendFormat(b, timeFormat)
	b = append(b, '"')
	return b, nil
}

func (t Time) String() string {
	return time.Time(t).Format(timeFormat)
}


运行结果:

转换后结构体:{Id:5 Birthday:2022-05-19 16:09:51}
转换后json:{"id":1,"birthday":"2022-05-19 16:09:51"}
  • 参考
    https://blog.csdn.net/DisMisPres/article/details/119178013