douxi3554
2016-08-20 21:32
浏览 211

JSON解码为接口{}时会生成map [string] interface {},而不是结构

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?

图片转代码服务由CSDN问答提供 功能建议

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

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongzhanlian6289 2016-08-20 23:55
    已采纳

    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)
    }
    
    已采纳该答案
    打赏 评论