mirror of
https://github.com/golang/go
synced 2024-11-19 01:54:39 -07: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:
parent
1d2955a2af
commit
df52d2ebd1
@ -696,12 +696,12 @@ type ptrEncoder struct {
|
||||
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() {
|
||||
e.WriteString("null")
|
||||
return
|
||||
}
|
||||
pe.elemEnc(e, v.Elem(), false)
|
||||
pe.elemEnc(e, v.Elem(), quoted)
|
||||
}
|
||||
|
||||
func newPtrEncoder(t reflect.Type) encoderFunc {
|
||||
|
@ -452,3 +452,29 @@ func TestHTMLEscape(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user