From 5a0d3f3b2acc9d9ec3d5ee5c098797fd6be19565 Mon Sep 17 00:00:00 2001 From: Victor Starodub Date: Fri, 15 Apr 2016 15:56:29 +0300 Subject: [PATCH] Fixes #20: Support non-builtin types for maps. --- gen/decoder.go | 4 ++-- gen/encoder.go | 2 +- tests/data.go | 9 ++++++++- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/gen/decoder.go b/gen/decoder.go index c831d49..476130c 100644 --- a/gen/decoder.go +++ b/gen/decoder.go @@ -113,13 +113,13 @@ func (g *Generator) genTypeDecoder(t reflect.Type, out string, indent int) error fmt.Fprintln(g.out, ws+"} else {") fmt.Fprintln(g.out, ws+" in.Delim('{')") fmt.Fprintln(g.out, ws+" if !in.IsDelim('}') {") - fmt.Fprintln(g.out, ws+" "+out+" = make("+g.getType(t)+")") + fmt.Fprintln(g.out, ws+" "+out+" = make(map["+g.getType(t.Key())+"]"+g.getType(t.Elem())+")") fmt.Fprintln(g.out, ws+" } else {") fmt.Fprintln(g.out, ws+" "+out+" = nil") fmt.Fprintln(g.out, ws+" }") fmt.Fprintln(g.out, ws+" for !in.IsDelim('}') {") - fmt.Fprintln(g.out, ws+" key := in.String()") + fmt.Fprintln(g.out, ws+" key := "+g.getType(t.Key())+"(in.String())") fmt.Fprintln(g.out, ws+" in.WantColon()") fmt.Fprintln(g.out, ws+" var "+tmpVar+" "+g.getType(elem)) diff --git a/gen/encoder.go b/gen/encoder.go index d55a4a6..4579da6 100644 --- a/gen/encoder.go +++ b/gen/encoder.go @@ -99,7 +99,7 @@ func (g *Generator) genTypeEncoder(t reflect.Type, in string, indent int) error fmt.Fprintln(g.out, ws+" for "+tmpVar+"_name, "+tmpVar+"_value := range "+in+" {") fmt.Fprintln(g.out, ws+" if !"+tmpVar+"_first { out.RawByte(',') }") fmt.Fprintln(g.out, ws+" "+tmpVar+"_first = false") - fmt.Fprintln(g.out, ws+" out.String("+tmpVar+"_name)") + fmt.Fprintln(g.out, ws+" out.String(string("+tmpVar+"_name))") fmt.Fprintln(g.out, ws+" out.RawByte(':')") g.genTypeEncoder(t.Elem(), tmpVar+"_value", indent+2) diff --git a/tests/data.go b/tests/data.go index cf4e79b..30d87d6 100644 --- a/tests/data.go +++ b/tests/data.go @@ -374,19 +374,26 @@ var excludedFieldValue = ExcludedField{ } var excludedFieldString = `{"process":true}` +type Str string + type Maps struct { Map map[string]string InterfaceMap map[string]interface{} NilMap map[string]string + + CustomMap map[Str]Str } var mapsValue = Maps{ Map: map[string]string{"A": "b"}, // only one item since map iteration is randomized InterfaceMap: map[string]interface{}{"G": float64(1)}, + + CustomMap: map[Str]Str{"c": "d"}, } var mapsString = `{` + `"Map":{"A":"b"},` + `"InterfaceMap":{"G":1},` + - `"NilMap":null` + + `"NilMap":null,` + + `"CustomMap":{"c":"d"}` + `}`