Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: UnmarshalJSON of dst not called when gjson.Scan #3769 #3770

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions encoding/gjson/gjson_z_unit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
package gjson_test

import (
"encoding/json"
"fmt"
"testing"

Expand Down Expand Up @@ -615,3 +616,29 @@ func Test_Issue2520(t *testing.T) {
t.Assert(gjson.MustEncodeString(t2), gjson.New(t2).MustToJsonString())
})
}

type UserIssue3769 struct {
Id string
}

func (u *UserIssue3769) UnmarshalJSON(data []byte) error {
var um map[string]string
err := json.Unmarshal(data, &um)
if err != nil {
return err
}

if v, ok := um["uid"]; ok {
u.Id = v
}
return nil
}

func TestIssue(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
data := `{"uid": "123", "uname": "456"}`
var u UserIssue3769
t.AssertNil(gjson.New(data).Scan(&u))
t.Assert(u.Id, `123`)
})
}
15 changes: 15 additions & 0 deletions util/gconv/gconv_scan.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
package gconv

import (
stdjson "encoding/json"
"reflect"

"github.com/gogf/gf/v2/errors/gcode"
Expand Down Expand Up @@ -197,6 +198,20 @@ func doConvertWithJsonCheck(srcValue interface{}, dstPointer interface{}) (ok bo
}

default:
switch dst := dstPointer.(type) {
case stdjson.Unmarshaler:
bytes, err := json.Marshal(srcValue)
if err != nil {
return false, err
}

err = dst.UnmarshalJSON(bytes)
if err != nil {
return false, err
}
return true, nil
}

// The `params` might be struct that implements interface function Interface, eg: gvar.Var.
if v, ok := srcValue.(localinterface.IInterface); ok {
return doConvertWithJsonCheck(v.Interface(), dstPointer)
Expand Down
Loading