FAQ
Reviewers: golang-dev_googlegroups.com,

Message:
Hello golang-dev@googlegroups.com (cc: golang-dev@googlegroups.com),

I'd like you to review this change to
https://code.google.com/p/go/


Description:
encoding/json: encode map key is of string kind, decode only of string
type

Allows encoding and decoding of maps with key of string kind, not just
string type.
Fixes issue 3519.

Please review this at https://codereview.appspot.com/6943047/

Affected files:
M src/pkg/encoding/json/decode.go
M src/pkg/encoding/json/decode_test.go


Index: src/pkg/encoding/json/decode.go
===================================================================
--- a/src/pkg/encoding/json/decode.go
+++ b/src/pkg/encoding/json/decode.go
@@ -436,9 +436,9 @@
)
switch v.Kind() {
case reflect.Map:
- // map must have string type
+ // map must have string kind
t := v.Type()
- if t.Key() != reflect.TypeOf("") {
+ if t.Key().Kind() != reflect.TypeOf("").Kind() {
d.saveError(&UnmarshalTypeError{"object", v.Type()})
break
}
@@ -547,7 +547,9 @@
// Write value back to map;
// if using struct, subv points into struct already.
if mv.IsValid() {
- mv.SetMapIndex(reflect.ValueOf(key), subv)
+ kv := reflect.New(v.Type().Key())
+ kv.Elem().SetString(key)
+ mv.SetMapIndex(kv.Elem(), subv)
}

// Next token must be , or }.
Index: src/pkg/encoding/json/decode_test.go
===================================================================
--- a/src/pkg/encoding/json/decode_test.go
+++ b/src/pkg/encoding/json/decode_test.go
@@ -1000,3 +1000,25 @@
t.Errorf("Unmarshal of null values affected primitives")
}
}
+
+func TestStringKind(t *testing.T) {
+ type stringKind string
+ type aMap map[stringKind]int
+
+ m := aMap{stringKind("foo"): 42}
+ b := new(bytes.Buffer)
+ NewEncoder(b).Encode(m)
+
+ expected := `{"foo":42}`
+ actual := strings.TrimSpace(b.String())
+ if actual != expected {
+ t.Errorf("Expected: %v, Got: %v", expected, actual)
+ }
+
+ var n aMap
+ NewDecoder(b).Decode(&n)
+
+ if len(n) != 1 || n["foo"] != 42 {
+ t.Errorf("StringKind not decoded correctly")
+ }
+}

Search Discussions

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-dev @
categoriesgo
postedDec 13, '12 at 5:21p
activeDec 13, '12 at 10:22p
posts5
users2
websitegolang.org

2 users in discussion

Ryanslade: 4 posts Rsc: 1 post

People

Translate

site design / logo © 2022 Grokbase