encoding/json: call (*T).MarshalJSON for addressable T values.

Fixes #2170.

R=golang-dev, cw, adg
CC=golang-dev
https://golang.org/cl/5618045
This commit is contained in:
David Symonds 2012-02-03 11:15:06 +11:00
parent 102638cb53
commit bf89d58e73
3 changed files with 74 additions and 2 deletions

View file

@ -262,8 +262,18 @@ func (e *encodeState) reflectValueQuoted(v reflect.Value, quoted bool) {
return
}
if j, ok := v.Interface().(Marshaler); ok && (v.Kind() != reflect.Ptr || !v.IsNil()) {
b, err := j.MarshalJSON()
m, ok := v.Interface().(Marshaler)
if !ok {
// T doesn't match the interface. Check against *T too.
if v.Kind() != reflect.Ptr && v.CanAddr() {
m, ok = v.Addr().Interface().(Marshaler)
if ok {
v = v.Addr()
}
}
}
if ok && (v.Kind() != reflect.Ptr || !v.IsNil()) {
b, err := m.MarshalJSON()
if err == nil {
// copy JSON into buffer, checking validity.
err = Compact(&e.Buffer, b)