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 ",测试的好像不行。
https://golang.org/pkg/time/#...
可以看到 Duration 的定义是
type Duration int64
,直接用 int64 就好了。或者可以自定义一个结构 embed time.Duration 类型,再写一个
UnmarshalJSON([]byte) error
序列化方法,但讲道理没有意义,最后用的时候还是要写一个转换time.Duration(Duration)
。我推荐上一种用法。可以参考下下面这个爆栈的讨论。
https://stackoverflow.com/que...