golang反序列化遇到的问题及解决方案

本文探讨了在Golang中处理JSON反序列化时遇到的两个问题:一是同一字段存在int和string类型,二是如何将JSON中的时间字符串转换为time.Time。解决方案包括在结构体中使用json tag来处理多类型字段,并自定义time类型以实现MarshalJSON和UnmarshalJSON方法,以正确解析时间戳。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.youkuaiyun.com/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.youkuaiyun.com/DisMisPres/article/details/119178013
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值