From 85caa40a3dce9d5f9af862ef98f8aa643b93525e Mon Sep 17 00:00:00 2001 From: John Date: Wed, 27 Nov 2019 23:38:33 +0800 Subject: [PATCH] fix issue in empty slice converting panic for gconv.Struct --- .example/other/test.go | 53 +++++++++++++++++++++++++++++--------- util/gconv/gconv_struct.go | 6 ++--- 2 files changed, 44 insertions(+), 15 deletions(-) diff --git a/.example/other/test.go b/.example/other/test.go index cae1bef07..c56cf5fa5 100644 --- a/.example/other/test.go +++ b/.example/other/test.go @@ -1,19 +1,48 @@ package main import ( + "github.com/gogf/gf/encoding/gjson" "github.com/gogf/gf/frame/g" - "github.com/gogf/gf/net/ghttp" + "github.com/gogf/gf/util/gconv" ) -func main() { - s := g.Server() - s.SetIndexFolder(true) - s.BindHandler("/admin.html", func(r *ghttp.Request) { - r.Response.Write("admin") - }) - s.BindHandler("/admin-do-{page}.html", func(r *ghttp.Request) { - r.Response.Write("admin-do-" + r.GetString("page")) - }) - s.SetPort(8999) - s.Run() +// +type BaseData struct { + Title string `json:"title"` + Content string `json:"content"` + BeginTime int64 `json:"begin_time"` + EndTime int64 `json:"end_time"` +} + +// 奖励数据 +type RewardOneData struct { + Type string `json:"type"` + Id uint32 `json:"id"` + Count uint32 `json:"count"` +} + +// 邮件 +type MailOneData struct { + Base BaseData `json:"base"` + MailId uint32 `json:"mail_id"` + PicId uint32 `json:"pic_id"` + PlayerList g.ArrayStr `json:"player_list"` + Reward []RewardOneData `json:"reward"` +} + +func main() { + test() +} + +func test() { + // 使用下面这行就会panic 原因是 最后的reward字段列表为空 + jsonStr := "{\"base\":{\"title\":\"testTitle\",\"content\":\"testContent\",\"begin_time\":1574763804,\"end_time\":1574767404},\"mail_id\":1,\"pic_id\":1,\"player_list\":[],\"reward\":[]}" + //jsonStr := "{\"base\":{\"title\":\"testTitle\",\"content\":\"testContent\",\"begin_time\":1574763804,\"end_time\":1574767404},\"mail_id\":1,\"pic_id\":1,\"player_list\":[],\"reward\":[{\"type\":\"diamond\",\"id\":0,\"count\":100}]}" + decodeData, _ := gjson.Decode(jsonStr) + + decodeMailData := new(MailOneData) + gconv.Struct(decodeData, decodeMailData) + + // + g.Dump(decodeMailData) } diff --git a/util/gconv/gconv_struct.go b/util/gconv/gconv_struct.go index 07319b729..2816e17d1 100644 --- a/util/gconv/gconv_struct.go +++ b/util/gconv/gconv_struct.go @@ -243,9 +243,7 @@ func bindVarToReflectValue(structFieldValue reflect.Value, value interface{}) er } // 属性为数组类型 - case reflect.Slice: - fallthrough - case reflect.Array: + case reflect.Slice, reflect.Array: a := reflect.Value{} v := reflect.ValueOf(value) if v.Kind() == reflect.Slice || v.Kind() == reflect.Array { @@ -267,6 +265,8 @@ func bindVarToReflectValue(structFieldValue reflect.Value, value interface{}) er a.Index(i).Set(e) } } + } else { + a = reflect.MakeSlice(structFieldValue.Type(), v.Len(), v.Len()) } } else { a = reflect.MakeSlice(structFieldValue.Type(), 1, 1)