Skip to content

Commit

Permalink
fix: UnmarshalJSON of dst not called when gjson.Scan gogf#3769
Browse files Browse the repository at this point in the history
  • Loading branch information
wlynxg committed Sep 12, 2024
1 parent 6b3fb60 commit a580104
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
29 changes: 29 additions & 0 deletions encoding/gjson/gjson_z_unit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
package gjson_test

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

"github.com/gogf/gf/v2/container/gmap"
Expand Down Expand Up @@ -615,3 +617,30 @@ 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))
log.Println(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

0 comments on commit a580104

Please sign in to comment.