广告
返回顶部
首页 > 资讯 > 后端开发 > GO >Golang 中的json.Marshal问题总结(推荐)
  • 855
分享到

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

2024-04-02 19:04:59 855人浏览 八月长安
摘要

目录1.Quiz2.Answer3.ResolvingConclusion1.Quiz 有如下一个例子: package main import ( "encoding/JSON

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)
}

到此这篇关于Golang 中的json.Marshal问题总结的文章就介绍到这了,更多相关Golang json.Marshal内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

您可能感兴趣的文档:

--结束END--

本文标题: Golang 中的json.Marshal问题总结(推荐)

本文链接: https://www.lsjlt.com/news/152777.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作