Skip to content

Commit

Permalink
Merge pull request #32 from wetor/fix-json-unmarshal
Browse files Browse the repository at this point in the history
🐞 fix: zjson.Unmarshal map data
  • Loading branch information
sohaha authored Jun 22, 2024
2 parents df47631 + 36e9bfa commit 181ab62
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 15 deletions.
24 changes: 9 additions & 15 deletions zjson/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -1983,21 +1983,15 @@ func assign(jsval *Res, val reflect.Value, fmap *fieldMaps) {
key := t.Key()
s := key.Kind() == reflect.String
if s {
kind := t.Elem().Kind()
switch kind {
case reflect.Interface:
val.Set(zreflect.ValueOf(jsval.Value()))
case reflect.Struct, reflect.Ptr:
v := reflect.MakeMap(t)
jsval.ForEach(func(key, value *Res) bool {
newval := reflect.New(t.Elem())
elem := newval.Elem()
assign(value, elem, fmap)
v.SetMapIndex(zreflect.ValueOf(key.Value()), elem)
return true
})
val.Set(v)
}
v := reflect.MakeMap(t)
jsval.ForEach(func(key, value *Res) bool {
newval := reflect.New(t.Elem())
elem := newval.Elem()
assign(value, elem, fmap)
v.SetMapIndex(zreflect.ValueOf(key.Value()), elem)
return true
})
val.Set(v)
}
case reflect.Interface:
val.Set(zreflect.ValueOf(jsval.Value()))
Expand Down
26 changes: 26 additions & 0 deletions zjson/get_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,32 @@ func TestUnmarshal(t *testing.T) {
tt.Equal("n1", s.IDs[0].Gg.P[0].Name)
}

func TestUnmarshal2(t *testing.T) {
tt := zlsgo.NewTest(t)
json := `{"u1":[{"name":"HH","id":1},{"name":"HBB","id":2}]}`
var m map[string][]map[string]any
err := Unmarshal(json, &m)
tt.NoError(err)
tt.Logf("%+v", m)
tt.Equal("HH", m["u1"][0]["name"])
tt.Equal(2.0, m["u1"][1]["id"])

json = `{"u2":{"u3":1}}`
var m2 map[string]map[string]any
err = Unmarshal(json, &m2)
tt.NoError(err)
tt.Logf("%+v", m2)
tt.Equal(1.0, m2["u2"]["u3"])

json = `{"u4":2}`
var m3 map[string]int
err = Unmarshal(json, &m3)
tt.NoError(err)
tt.Logf("%+v", m3)
tt.Equal(2, m3["u4"])

}

func TestEditJson(t *testing.T) {
tt := zlsgo.NewTest(t)
j := Parse(demo)
Expand Down

0 comments on commit 181ab62

Please sign in to comment.