JSON解码为interface{}的结构,返回的是map[string]interface{},而不是struct。

huangapple go评论164阅读模式
英文:

JSON decode into struct as interface{} yields map[string]interface{}, not struct

问题

这里有一个复制了问题的 Go Playground:
https://play.golang.org/p/GgHsLffp1G

基本上,我正在尝试编写一个函数,该函数接受一个结构体,并返回一个可以将 HTTP 请求解码为该类型的函数。不幸的是,一些类型信息丢失了,返回的类型是 map[string]interface{} 而不是正确的结构体类型。我该如何向 JSON 解码器传递正确的类型?JSON unmarshal 是否会更好地工作?

英文:

Here is a go playground replicating the issue:
https://play.golang.org/p/GgHsLffp1G

Basically, I'm trying to write a function that takes a struct and returns a function that can decode http requests as that type. Unfortunately some type information is being lost and the type being returned is a map[string]interface{} and not the correct struct type. How can I communicate the correct type to the JSON decoder? Would JSON unmarshal work better?

答案1

得分: 1

这似乎有效:

Playground

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)
}
英文:

This seems to work:

Playground

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)
}

huangapple
  • 本文由 发表于 2016年8月21日 05:32:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/39058902.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定