improve gjson.New by using gconv.MapDeep for map/struct

This commit is contained in:
John 2020-09-07 19:44:11 +08:00
parent bdb4fd0d25
commit ad943c5e02
4 changed files with 29 additions and 7 deletions

View File

@ -55,8 +55,10 @@ func NewWithTag(data interface{}, tags string, safe ...bool) *Json {
}
}
default:
rv := reflect.ValueOf(data)
kind := rv.Kind()
var (
rv = reflect.ValueOf(data)
kind = rv.Kind()
)
if kind == reflect.Ptr {
rv = rv.Elem()
kind = rv.Kind()
@ -72,9 +74,7 @@ func NewWithTag(data interface{}, tags string, safe ...bool) *Json {
}
case reflect.Map, reflect.Struct:
i := interface{}(nil)
// Note that it uses Map function implementing the converting.
// Note that it here should not use MapDeep function if you really know what it means.
i = gconv.Map(data, tags)
i = gconv.MapDeep(data, tags)
j = &Json{
p: &i,
c: byte(gDEFAULT_SPLIT_CHAR),

View File

@ -47,3 +47,25 @@ func Test_Load_NewWithTag(t *testing.T) {
t.Assert(j.Get("addr-json"), nil)
})
}
func Test_Load_New_CustomStruct(t *testing.T) {
type Base struct {
Id int
}
type User struct {
Base
Name string
}
user := new(User)
user.Id = 1
user.Name = "john"
gtest.C(t, func(t *gtest.T) {
j := gjson.New(user)
t.AssertNE(j, nil)
s, err := j.ToJsonString()
t.Assert(err, nil)
t.Assert(s == `{"Id":1,"Name":"john"}` || s == `{"Name":"john","Id":1}`, true)
})
}

View File

@ -10,7 +10,7 @@ import (
"github.com/gogf/gf/encoding/gjson"
)
// New creates a Parser object with any variable type of <data>, but <data> should be a map or
// New creates a Parser object with any variable type of <data>, but <data> should be a map, struct or
// slice for data access reason, or it will make no sense.
//
// The parameter <safe> specifies whether using this Json object in concurrent-safe context, which

View File

@ -37,7 +37,7 @@ func MapDeep(value interface{}, tags ...string) map[string]interface{} {
// doMapConvert implements the map converting.
// It automatically checks and converts json string to map if <value> is string/[]byte.
//
// TODO completely implement the recursive converting for all types.
// TODO completely implement the recursive converting for all types, especially the map.
func doMapConvert(value interface{}, recursive bool, tags ...string) map[string]interface{} {
if value == nil {
return nil