Skip to content

Commit

Permalink
fix: map keys being string type definitions
Browse files Browse the repository at this point in the history
Co-authored-by: Marcela Campo <mcampo@pivotal.io>
  • Loading branch information
blgm and pivotal-marcela-campo committed Oct 1, 2020
1 parent 1474c63 commit d42ff3e
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
6 changes: 6 additions & 0 deletions marshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,12 @@ var _ = Describe("Marshal", func() {
mn := map[int]interface{}{4: 3}
expectToFail(struct{ M map[int]interface{} }{M: mn}, `maps must only have string keys for "map[int]interface {}" at field "M" (type "map[int]interface {}")`)
})

It("marshals a map with keys that are string type definitions", func() {
type stringy string
me := map[stringy]string{"foo": "hello"}
expectToMarshal(struct{ M map[stringy]string }{M: me}, `{"M":{"foo": "hello"}}`)
})
})

It("marshals a json.Marshaler", func() {
Expand Down
4 changes: 2 additions & 2 deletions unmarshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ func unmarshalIntoSlice(ctx context.Context, target reflect.Value, found bool, s
func unmarshalIntoMap(ctx context.Context, target reflect.Value, found bool, source interface{}) error {
targetType := underlyingType(target)

if targetType.Key() != reflect.TypeOf("") {
if targetType.Key().Kind() != reflect.String {
return newUnsupportedKeyTypeError(ctx, targetType.Key())
}

Expand All @@ -210,7 +210,7 @@ func unmarshalIntoMap(ctx context.Context, target reflect.Value, found bool, sou
return err
}

m.SetMapIndex(reflect.ValueOf(k), targetValue)
m.SetMapIndex(reflect.ValueOf(k).Convert(targetType.Key()), targetValue)
}

return nil
Expand Down
9 changes: 8 additions & 1 deletion unmarshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -400,10 +400,17 @@ var _ = Describe("Unmarshal", func() {
})
})

It("rejects an map field that does not have string keys", func() {
It("rejects a map field that does not have string keys", func() {
var s struct{ S map[int]string }
expectToFail(&s, `{}`, `maps must only have string keys for "int" at field "S" (type "map[int]string")`)
})

It("unmarshals a map with keys that are string type definitions", func() {
type stringy string
var s struct{ S map[stringy]string }
unmarshal(&s, `{"S": { "data": "some-data" } }`)
Expect(s.S).To(Equal(map[stringy]string{"data": "some-data"}))
})
})

It("unmarshals into json.Unmarshaler field", func() {
Expand Down

0 comments on commit d42ff3e

Please sign in to comment.