为某个类型实现MarshalJSON()([]byte, error)和UnmarshalJSON(b []byte) error方法,那么该类型在序列化和反序列化时就会使用相应方法。
未自定义前代码:
package main
import (
"encoding/json"
"fmt"
"time"
)
type Student struct {
Name string `json:"name"`
Age int `json:"age"`
Weight float64 `json:"weight"`
Height float64 `json:"height"`
RecordTime time.Time `json:"recordtime"`
}
func main() {
s1 := Student{
Name: "jack",
Age: 20,
Weight: 61.5,
Height: 172.5,
RecordTime: time.Now(),
}
b, err := json.Marshal(s1)
if err != nil {
fmt.Printf("json.Marshal failed, err:%v\n", err)
return
}
fmt.Printf("s1: %s\n", b)
var s2 Student
err = json.Unmarshal(b, &s2)
if err != nil {
fmt.Printf("json.Unmarshal failed, err:%v\n", err)
return
}
fmt.Printf("s2: %#v\n", s2)
}
输出:
s1: {"name":"jack","age":20,"weight":61.5,"height":172.5,"recordtime":"2020-06-24T17:07:57.200873+08:00"}
s2: main.Student{Name:"jack", Age:20, Weight:61.5, Height:172.5, RecordTime:time.Time{wall:0xbf91428, ext:63728586477, loc:(*time.Location)(0x11d0d60)}}
自定义MarshalJSON()([]byte, error)和UnmarshalJSON(b []byte) error方法:
package main
import (
"encoding/json"
"fmt"
"time"
)
type Student struct {
Name string `json:"name"`
Age int `json:"age"`
Weight float64 `json:"weight"`
Height float64 `json:"height"`
RecordTime time.Time `json:"recordtime"`
}
const layout = "2006-01-02 15:04:05"
func (s *Student) MarshalJSON() ([]byte, error) {
type TempStudent Student
return json.Marshal(struct {
RecordTime string `json:"recordtime"`
*TempStudent
}{
RecordTime: s.RecordTime.Format(layout),
TempStudent: (*TempStudent)(s),
})
}
func (s *Student) UnmarshalJSON(data []byte) error {
type TempStudent Student
ss := struct {
RecordTime string `json:"recordtime"`
*TempStudent
}{
TempStudent: (*TempStudent)(s),
}
if err := json.Unmarshal(data, &ss); err != nil {
return err
}
var err error
s.RecordTime, err = time.Parse(layout, ss.RecordTime)
if err != nil {
return err
}
return nil
}
func main() {
s1 := Student{
Name: "jack",
Age: 20,
Weight: 61.5,
Height: 172.5,
RecordTime: time.Now(),
}
b, err := json.Marshal(&s1)
if err != nil {
fmt.Printf("json.Marshal failed, err:%v\n", err)
return
}
fmt.Printf("s1: %s\n", b)
var s2 Student
err = json.Unmarshal(b, &s2)
if err != nil {
fmt.Printf("json.Unmarshal failed, err:%v\n", err)
return
}
fmt.Printf("s2: %#v\n", s2)
}
输出:
s1: {"recordtime":"2020-06-24 17:41:14","name":"jack","age":20,"weight":61.5,"height":172.5}
s2: main.Student{Name:"jack", Age:20, Weight:61.5, Height:172.5, RecordTime:time.Time{wall:0x0, ext:63728617274, loc:(*time.Location)(nil)}}