Golang的encoding/json Marshaler

huangapple go评论78阅读模式
英文:

Golang encoding/json Marshaler

问题

根据encoding/json包的文档所述,

> Marshal会递归地遍历值v。
> 如果遇到的值实现了Marshaler接口
> 并且不是nil指针,Marshal会调用其MarshalJSON方法
> 来生成JSON。

在代码的哪个位置执行这个测试呢?也就是说,encoding/json是如何检查类型为t的值v是否实现了Marshaller接口的?

英文:

As stated in the encoding/json package documentation,

> 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.

Where exactly in the code is this test performed?

In another terms, how does encoding/json check if a value v of type t implements the Marshaller interface?

答案1

得分: 2

这里:

https://stackoverflow.com/questions/31074404/golang-encoding-json-marshaler/31074533?noredirect=1#comment50172792_31074533

if t.Implements(marshalerType) {
	return marshalerEncoder
}

编辑:
上面的链接已经更新,指向了Go的一个特定版本,正如下面的评论中@dave-c指出的那样。

英文:

Here :

https://stackoverflow.com/questions/31074404/golang-encoding-json-marshaler/31074533?noredirect=1#comment50172792_31074533

if t.Implements(marshalerType) {
	return marshalerEncoder
}

Edit:
The link above has been updated to point to a specific version of Go, as @dave-c pointed out in comments below.

huangapple
  • 本文由 发表于 2015年6月26日 21:25:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/31074404.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定