经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » JSON » 查看文章
Golang?中的json.Marshal问题总结(推荐)
来源:jb51  时间:2022/6/27 16:57:51  对本文有异议

1.Quiz

有如下一个例子:

  1. package main
  2.  
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "time"
  7. )
  8.  
  9. type RecordBrief struct {
  10. time.Time
  11. ID int
  12. }
  13.  
  14. func main() {
  15. r := RecordBrief{
  16. Time: time.Now(),
  17. ID: 6,
  18. }
  19. m, _ := json.MarshalIndent(r, "", "\t")
  20. fmt.Println(string(m))
  21. }

你期望的结果是像:

{
        "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的注释文档中的一个解释:

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

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

然后我们再看看time.Time

  1. type Time struct {
  2. ...
  3. }
  4.  
  5. // MarshalJSON implements the json.Marshaler interface.
  6. // The time is a quoted string in RFC 3339 format, with sub-second precision added if present.
  7. func (t Time) MarshalJSON() ([]byte, error) {
  8. if y := t.Year(); y < 0 || y >= 10000 {
  9. // RFC 3339 is clear that years are 4 digits exactly.
  10. // See golang.org/issue/4556#c15 for more discussion.
  11. return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
  12. }
  13.  
  14. b := make([]byte, 0, len(RFC3339Nano)+2)
  15. b = append(b, '"')
  16. b = t.AppendFormat(b, RFC3339Nano)
  17. b = append(b, '"')
  18. return b, nil
  19. }

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

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

  1. type RecordBrief struct {
  2. time.Time
  3. ID int
  4. }

为什么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作为一个非匿名的导出字段:

  1. type RecordBrief struct {
  2. Time time.Time
  3. ID int
  4. }

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

  1. type RecordBrief struct {
  2. time.Time
  3. ID int
  4. }
  5. func (r RecordBrief) MarshalJSON() ([]byte, error) {
  6. //非常简单的一种方式就是创建中间类型
  7. t := struct {
  8. Time time.Time
  9. ID int
  10. }{
  11. r.Time,
  12. r.ID,
  13. }
  14. return json.Marshal(t)
  15. }

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号