小编典典

JSON解码为interface {}产生的结构体产生map [string] interface {},而不是struct

go

这是一个复制问题的游乐场:https :
//play.golang.org/p/GgHsLffp1G

基本上,我正在尝试编写一个带有结构并返回可以将http请求解码为该类型的函数的函数。不幸的是,一些类型信息丢失了,返回的类型是map [string]
interface {}而不是正确的结构类型。如何将正确的类型传达给JSON解码器?JSON解组会更好吗?


阅读 321

收藏
2020-07-02

共1个答案

小编典典

这似乎可行:

操场

func requestParser(i interface{}) parser {
    return func(r io.Reader) (interface{}, error) {
        json.NewDecoder(r).Decode(i)
        return reflect.ValueOf(i).Elem(), nil
    }
}

func main() {
    var foo Foo
    s := "{\"Name\":\"Logan\"}"
    p := requestParser(&foo)
}
2020-07-02