From 4d9db6edf0b9684a576474872ea2e59ef1e898ac Mon Sep 17 00:00:00 2001 From: John Date: Mon, 18 May 2020 20:58:19 +0800 Subject: [PATCH] improve package gconv for map converting --- encoding/gjson/gjson_z_unit_json_test.go | 39 +++++++++++++++++++++++- util/gconv/gconv.go | 10 ++++++ util/gconv/gconv_struct.go | 2 +- 3 files changed, 49 insertions(+), 2 deletions(-) diff --git a/encoding/gjson/gjson_z_unit_json_test.go b/encoding/gjson/gjson_z_unit_json_test.go index 86f09d37d..e2d113cff 100644 --- a/encoding/gjson/gjson_z_unit_json_test.go +++ b/encoding/gjson/gjson_z_unit_json_test.go @@ -8,6 +8,7 @@ package gjson_test import ( "github.com/gogf/gf/encoding/gjson" + "github.com/gogf/gf/frame/g" "github.com/gogf/gf/test/gtest" "github.com/gogf/gf/text/gstr" "testing" @@ -44,5 +45,41 @@ func Test_ToJson(t *testing.T) { t.Assert(gstr.Contains(content, `"id":"g0936lt1u0f"`), true) t.Assert(gstr.Contains(content, `"new":"4"`), true) }) - +} + +func Test_MapAttributeConvert(t *testing.T) { + var data = ` + { + "title": {"l1":"标签1","l2":"标签2"} +} +` + gtest.C(t, func(t *gtest.T) { + j, err := gjson.LoadContent(data) + gtest.Assert(err, nil) + + tx := struct { + Title map[string]interface{} + }{} + + err = j.ToStruct(&tx) + gtest.Assert(err, nil) + t.Assert(tx.Title, g.Map{ + "l1": "标签1", "l2": "标签2", + }) + }) + + gtest.C(t, func(t *gtest.T) { + j, err := gjson.LoadContent(data) + gtest.Assert(err, nil) + + tx := struct { + Title map[string]string + }{} + + err = j.ToStruct(&tx) + gtest.Assert(err, nil) + t.Assert(tx.Title, g.Map{ + "l1": "标签1", "l2": "标签2", + }) + }) } diff --git a/util/gconv/gconv.go b/util/gconv/gconv.go index 3cce2c652..a14f2eabe 100644 --- a/util/gconv/gconv.go +++ b/util/gconv/gconv.go @@ -119,6 +119,16 @@ func Convert(i interface{}, t string, params ...interface{}) interface{} { case "Duration", "time.Duration": return Duration(i) + + case "map[string]string": + return MapStrStr(i) + + case "map[string]interface{}": + return Map(i) + + case "[]map[string]interface{}": + return Maps(i) + default: return i } diff --git a/util/gconv/gconv_struct.go b/util/gconv/gconv_struct.go index bf253b9cc..da536327b 100644 --- a/util/gconv/gconv_struct.go +++ b/util/gconv/gconv_struct.go @@ -347,7 +347,7 @@ func bindVarToReflectValue(structFieldValue reflect.Value, value interface{}) (e defer func() { if e := recover(); e != nil { err = errors.New( - fmt.Sprintf(`cannot convert value "%d" to type "%s"`, + fmt.Sprintf(`cannot convert value "%+v" to type "%s"`, value, structFieldValue.Type().String(), ),