From: Paul Borman Date: Fri, 12 Jul 2013 02:34:09 +0000 (-0400) Subject: json: unmarshal types that are byte slices. X-Git-Tag: go1.2rc2~1076 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=59306493067a6ebcc50bc9dfd4a1d1af543bd2d8;p=gostls13.git json: unmarshal types that are byte slices. The json package cheerfully would marshal type S struct { IP net.IP } but would give an error when unmarshalling. This change allows any type whose concrete type is a byte slice to be unmarshalled from a string. Fixes #5086. R=golang-dev, rsc CC=golang-dev https://golang.org/cl/11161044 --- diff --git a/src/pkg/encoding/json/decode.go b/src/pkg/encoding/json/decode.go index 62ac294b89..e608ef4a61 100644 --- a/src/pkg/encoding/json/decode.go +++ b/src/pkg/encoding/json/decode.go @@ -660,7 +660,7 @@ func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool default: d.saveError(&UnmarshalTypeError{"string", v.Type()}) case reflect.Slice: - if v.Type() != byteSliceType { + if v.Type().Elem().Kind() != reflect.Uint8 { d.saveError(&UnmarshalTypeError{"string", v.Type()}) break } diff --git a/src/pkg/encoding/json/decode_test.go b/src/pkg/encoding/json/decode_test.go index f845f69ab7..97cbb4f09b 100644 --- a/src/pkg/encoding/json/decode_test.go +++ b/src/pkg/encoding/json/decode_test.go @@ -1191,3 +1191,32 @@ func TestSkipArrayObjects(t *testing.T) { t.Errorf("got error %q, want nil", err) } } + +// Test that types of byte slices (such as net.IP) both +// marshal and unmarshal. +func TestByteSliceType(t *testing.T) { + type A []byte + type S struct { + A A + } + + for x, in := range []S{ + S{}, + S{A: []byte{'1'}}, + S{A: []byte{'1', '2', '3', '4', '5'}}, + } { + data, err := Marshal(&in) + if err != nil { + t.Errorf("#%d: got Marshal error %q, want nil", x, err) + continue + } + var out S + err = Unmarshal(data, &out) + if err != nil { + t.Fatalf("#%d: got Unmarshal error %q, want nil", x, err) + } + if !reflect.DeepEqual(&out, &in) { + t.Fatalf("#%d: got %v, want %v", x, &out, &in) + } + } +} diff --git a/src/pkg/encoding/json/encode.go b/src/pkg/encoding/json/encode.go index ffe903a546..e25a9b8805 100644 --- a/src/pkg/encoding/json/encode.go +++ b/src/pkg/encoding/json/encode.go @@ -44,8 +44,8 @@ import ( // The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e" // to keep some browsers from misinterpreting JSON output as HTML. // -// Array and slice values encode as JSON arrays, except that -// []byte encodes as a base64-encoded string, and a nil slice +// Array and slice values encode as JSON arrays, except that a slice of +// bytes encodes as a base64-encoded string, and a nil slice // encodes as the null JSON object. // // Struct values encode as JSON objects. Each exported struct field