improve package gconv for map converting

This commit is contained in:
John
2020-05-18 20:58:19 +08:00
parent 38111a64e3
commit 4d9db6edf0
3 changed files with 49 additions and 2 deletions

View File

@ -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",
})
})
}

View File

@ -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
}

View File

@ -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(),
),