[英]Go Unmarshal reflect.Type got map[string]interface{}
I want to convert json string to some struct ,use as func param 我想将json字符串转换为某些结构,用作func参数
I use reflect to get Param Type,this work fine , 我使用反射来获取参数类型,这个工作很好,
but if I use json.Unmarshal
I always get map[string]interface{}
但是如果我使用
json.Unmarshal
我总会得到map[string]interface{}
this is a mini Run sample,File name is json_test.go
这是一个微型Run示例,文件名为
json_test.go
package testJson
import (
"reflect"
"encoding/json"
"testing"
"log"
)
type LoginForm struct {
Name string
}
func Login(login LoginForm) {
}
func TestRun(t *testing.T) {
_func := Login
f := reflect.ValueOf(_func)
funcType := f.Type()
paramType := funcType.In(0)
log.Print(paramType.Name())
v := reflect.New(paramType).Elem().Interface()
jsonstr := `{"Name":"123"}`
log.Print(jsonstr)
log.Print(reflect.TypeOf(v).Name())
log.Print("%+v", v)
err := json.Unmarshal([]byte(jsonstr), &v)
if err != nil {
panic(err)
}
log.Print(reflect.TypeOf(v).Name())
log.Print( v)
var in []reflect.Value
in = make([]reflect.Value, funcType.NumIn())
in[0] = reflect.ValueOf(v)
f.Call(in)
}
Thanks for your help! 谢谢你的帮助!
Don't reflect.New
a pointer type because the result of that is a pointer to the pointer, instead reflect.New
the Elem
of the pointer type. 不要
reflect.New
一个指针类型,因为其结果是指向该指针的指针,而不是reflect.New
。 reflect.New
一个指针类型的Elem
。
Change this: 更改此:
v := reflect.New(paramType).Elem().Interface()
To this: 对此:
v := reflect.New(paramType.Elem()).Interface()
At this point v
is already a pointer to LoginForm
so you don't need to get its address with &
when passing to Unmarshal
. 至此,
v
已经是一个指向LoginForm
的指针,因此在传递给Unmarshal
时,不需要使用&
来获取其地址。
https://play.golang.org/p/JM4fRXb7fo https://play.golang.org/p/JM4fRXb7fo
Also the reason you got map[string]interface{}
is because the return type of the Interface()
method is unsurprisingly enough interface{}
, so while v
's underlying type could be anything its "topmost" type is interface{}
. 同样,获得
map[string]interface{}
的原因是因为Interface()
方法的返回类型足够多的interface{}
就不足为奇了,所以尽管v
的基础类型可以是它的“最高”类型是interface{}
。 So then, doing &v
will get you *interface{}
as opposed to the inteded *LoginForm
. 因此,执行
&v
将使您获得*interface{}
,而不是原来的*LoginForm
。 And in the docs you can find that trying to unmarshal a JSON object into an interface{}
will result in a value of type map[string]interface{}
. 并且在文档中,您会发现尝试将JSON对象解组到
interface{}
会导致map[string]interface{}
类型的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.