网络编程
位置:首页>> 网络编程>> Go语言>> Golang 中的json.Marshal问题总结(推荐)

Golang 中的json.Marshal问题总结(推荐)

作者:加拉萨假期  发布时间:2024-02-16 04:20:22 

标签:Golang,json,Marshal

1.Quiz

有如下一个例子:

package main

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

type RecordBrief struct {
time.Time
ID int
}

func main() {
r := RecordBrief{
Time: time.Now(),
ID:   6,
}
m, _ := json.MarshalIndent(r, "", "\t")
fmt.Println(string(m))
}

你期望的结果是像:

{
        "Time": "2022-06-25T10:49:39.597537249+08:00",
        "ID": 6
}

还是:

{
        "ID": 6
}

或者是别的?

2.Answer

其实如果你认为的答案不是:

"2022-06-25T10:52:23.590933959+08:00"

也没能想明白原因,可以继续往下看看。

3.Resolving

诚然,我们在学习json的序列化和反序列化的时候,目的就是把一个Golang struct值序列化为对应的json string罢了。可能我们还知道一些Marshal的规则,比如struct的字段需要定义为可导出的,比如还可通过定义对应的json tag来修改struct field对应的json字段名称等。

但是对于json.Marshal函数的细节可能大家不会去太在意。本次提出的问题中,我们不难注意到其中的time.Time是一个匿名(Anonymous)字段,而这个就是答案的由来。我们先看看json.Marshal的注释文档中的一个解释:

// ...
// Marshal traverses the value v recursively.
// If an encountered value implements the Marshaler interface
// and is not a nil pointer, Marshal calls its MarshalJSON method
// to produce JSON. If no MarshalJSON method is present but the
// value implements encoding.TextMarshaler instead, Marshal calls
// its MarshalText method and encodes the result as a JSON string.
// ...
func Marshal(v interface{}) ([]byte, error) {
...
}

Marshal函数递归地遍历传入的序列化对象v(及其成员)。当面对一个实现了json.Marshaler接口的对象(不能是一个空指针)时,Marshal函数就会调用该对象的MarshalJSON方法来生成JSON内容。如果没有实现json.Marshaler,而是实现了encoding.TextMarshaler接口,那么就会调用它的MarshalText方法,然后把该方法返回的结果转编为一个JSON字符串。

然后我们再看看time.Time

type Time struct {
...
}

// MarshalJSON implements the json.Marshaler interface.
// The time is a quoted string in RFC 3339 format, with sub-second precision added if present.
func (t Time) MarshalJSON() ([]byte, error) {
if y := t.Year(); y < 0 || y >= 10000 {
// RFC 3339 is clear that years are 4 digits exactly.
// See golang.org/issue/4556#c15 for more discussion.
return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
}

b := make([]byte, 0, len(RFC3339Nano)+2)
b = append(b, '"')
b = t.AppendFormat(b, RFC3339Nano)
b = append(b, '"')
return b, nil
}

所以time.Time是实现了json.Marshaler接口的。然后观察到它的实现是把时间按照RFC3339Nano格式字符串值返回为json序列化结果,这和我们实际上运行程序看到的结果是一致的。

那么再看看我们的type定义:

type RecordBrief struct {
time.Time
ID int
}

为什么ID字段不见了?正是因为匿名字段的原因,Golang中的这种用法有点类似于继承,所以RecordBrief类型也自动具有了time.Time的所有方法,当然也包括了MarshalJSON,从而也就实现了json.Marshaler接口。如此一来,当一个RecordBrief被Marshal的时候,它的序列化结果就被time.Time的序列化结果给覆盖了。

Conclusion

如果你和我一样,没能一下知道原因,那多半是对一些常见的知识了解的深度和广度不够。我之前确实不知道time.Time居然也实现了json.Marshaler接口,也不清楚json.Marshal到底在做什么,所以不知道答案也就理所当然了,后来经过阅读文档注释,才终于对该问题有了一些认知(后续应该总结一篇json.Marshal的源码解析)。

至此,如果我们想要这种样子的结果:

{
        "Time": "2022-06-25T10:49:39.597537249+08:00",
        "ID": 6
}

最简单的方式是修改struct,将time.Time作为一个非匿名的导出字段:

type RecordBrief struct {
Time time.Time
ID int
}

另一种方法是给我们的RecordBrief实现json.Marshaler接口:

type RecordBrief struct {
time.Time
ID int
}
func (r RecordBrief) MarshalJSON() ([]byte, error) {
//非常简单的一种方式就是创建中间类型
t := struct {
Time time.Time
ID   int
}{
r.Time,
r.ID,
}
return json.Marshal(t)
}

来源:https://blog.csdn.net/m0_38059938/article/details/125456612

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com