golang-接收时间类型参数(自定义 json 的类型转换)

2023-04-17  本文已影响0人  爱吃豆包

先定义类型

实现 MarshalJSONUnmarshalJSON 函数

json.MarshalJSON 是用于转换为 json
json.UnmarshalJSON 用于解析值

如果在调用 json.UnmarshalJSON(jsonStr, &A{}) 进行解析值的时候,那么就会调用该类型实现的 UnmarshalJSON 函数,也就是说实现 MarshalJSONUnmarshalJSON 函数,我们可以自由的实现 json 的类型转换

package types

import (
    "database/sql"
    "encoding/json"
    "strconv"
    "time"
)

// json 转换 时间

type NullTime struct {
    sql.NullTime
}

// MarshalJSON 转换为 json
func (nt *NullTime) MarshalJSON(value interface{}) ([]byte, error) {
    if nt.Valid {
        return json.Marshal(nt.Time)
    } else {
        return json.Marshal(nil)
    }
}

// UnmarshalJSON 获取值
func (nt *NullTime) UnmarshalJSON(data []byte) error {

    var s *time.Time

    timeStr, _ := UnixToTime(string(data))
    s = &timeStr
    //if err := json.Unmarshal([]byte(timeStr)., &s); err != nil {
    //  return err
    //}
    if s != nil {
        nt.Valid = true
        nt.Time = *s
    } else {
        nt.Valid = false
    }
    return nil
}

func UnixToTime(e string) (datatime time.Time, err error) {
    data, err := strconv.ParseInt(e, 10, 64)
    datatime = time.Unix(data/1000, 0)
    return
}

使用定义好的类型

package params

import (
    "go-press/types"
)

type Base struct {
    Page      int            `form:"page" json:"page"`
    Size      int            `form:"size" json:"size"`
    StartDate types.NullTime `form:"start_date" json:"start_date"`
    EndDate   types.NullTime `form:"end_date" json:"end_date"`
}

那么在使用 json 转换的时候就会转换为我们要的值

base := &Base{}
json.UnmarshalJSON(jsonStr, base)
上一篇 下一篇

猜你喜欢

热点阅读