JSON解码为interface {}产生的结构体产生map [string] interface {},而不是struct [英] JSON decode into struct as interface{} yields map[string]interface{}, not struct

查看:95
本文介绍了JSON解码为interface {}产生的结构体产生map [string] interface {},而不是struct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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?

推荐答案

这似乎可行:

游乐场

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

这篇关于JSON解码为interface {}产生的结构体产生map [string] interface {},而不是struct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆