Golang中,json转struct时,将字符串转为 time.Duration 的类型

package main

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

type Student struct {
    Id     int           `json:"id"`
    Gender string        `json:"gender"`
    Name   string        `ison:"nane"`
    Sno    string        `json:"sno"`
    Tim    time.Duration `json:"time"` // 将字符串转为 time.Duration 格式
}

func main() {
    var s1 = Student{
        Id:     12,
        Gender: "男",
        Name:   "李四",
        Sno:    "001",
        Tim:    "2s",
    }

    fmt.Printf("%#v\n", s1)
    jsonByte, _ := json.Marshal(s1)
    jsonStr := string(jsonByte)
    fmt.Printf("%v", jsonStr)
}

有人提过json包的特殊用法“,string ",测试的好像不行。

阅读 5.2k
1 个回答

https://golang.org/pkg/time/#...

可以看到 Duration 的定义是 type Duration int64 ,直接用 int64 就好了。

type Student struct {
    Id     int           `json:"id"`
    Gender string        `json:"gender"`
    Name   string        `ison:"nane"`
    Sno    string        `json:"sno"`
    Tim    int64         `json:"time"`
}

或者可以自定义一个结构 embed time.Duration 类型,再写一个 UnmarshalJSON([]byte) error 序列化方法,但讲道理没有意义,最后用的时候还是要写一个转换 time.Duration(Duration)。我推荐上一种用法。

type MyDuration struct {
    time.Duration
}

func (d *MyDuration) UnmarshalJSON(data []byte) error {
   ...
}

type Student struct {
    Id     int           `json:"id"`
    Gender string        `json:"gender"`
    Name   string        `ison:"nane"`
    Sno    string        `json:"sno"`
    Tim    MyDuration    `json:"time"` // 将字符串转为 time.Duration 格式
}

可以参考下下面这个爆栈的讨论。

https://stackoverflow.com/que...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题