1
0
mirror of https://github.com/golang/go synced 2024-10-01 13:28:37 -06:00

encoding/json: make ,string work when encoding pointer fields

It was respected by unmarshal, but not marshal, so they didn't
round-trip.

Fixes #8582

LGTM=rsc
R=rsc
CC=golang-codereviews
https://golang.org/cl/132960043
This commit is contained in:
Brad Fitzpatrick 2014-08-25 10:32:46 -07:00
parent 1d2955a2af
commit df52d2ebd1
2 changed files with 28 additions and 2 deletions

View File

@ -696,12 +696,12 @@ type ptrEncoder struct {
elemEnc encoderFunc elemEnc encoderFunc
} }
func (pe *ptrEncoder) encode(e *encodeState, v reflect.Value, _ bool) { func (pe *ptrEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
if v.IsNil() { if v.IsNil() {
e.WriteString("null") e.WriteString("null")
return return
} }
pe.elemEnc(e, v.Elem(), false) pe.elemEnc(e, v.Elem(), quoted)
} }
func newPtrEncoder(t reflect.Type) encoderFunc { func newPtrEncoder(t reflect.Type) encoderFunc {

View File

@ -452,3 +452,29 @@ func TestHTMLEscape(t *testing.T) {
t.Errorf("HTMLEscape(&b, []byte(m)) = %s; want %s", b.Bytes(), want.Bytes()) t.Errorf("HTMLEscape(&b, []byte(m)) = %s; want %s", b.Bytes(), want.Bytes())
} }
} }
// golang.org/issue/8582
func TestEncodePointerString(t *testing.T) {
type stringPointer struct {
N *int64 `json:"n,string"`
}
var n int64 = 42
b, err := Marshal(stringPointer{N: &n})
if err != nil {
t.Fatalf("Marshal: %v", err)
}
if got, want := string(b), `{"n":"42"}`; got != want {
t.Errorf("Marshal = %s, want %s", got, want)
}
var back stringPointer
err = Unmarshal(b, &back)
if err != nil {
t.Fatalf("Unmarshal: %v", err)
}
if back.N == nil {
t.Fatalf("Unmarshalled nil N field")
}
if *back.N != 42 {
t.Fatalf("*N = %d; want 42", *back.N)
}
}