dongzhuo3376 2016-03-18 16:37
浏览 18
已采纳

解组为接口类型

I expected below code to print an object of type struct J, however it prints a map object of type map[string]interface{}. I can feel why it acts like that, however when I run, reflect.ValueOf(i).Kind(), it returns Struct, so it kinda gives me the impression that Unmarshal method should return type J instead of a map. Could anyone enlighten me ?

type J struct {
    Text string
}

func main() {
    j := J{}
    var i interface{} = j

    js := "{\"Text\": \"lala\"}"


    json.Unmarshal([]byte(js), &i)

    fmt.Printf("%#v", i)

}
  • 写回答

2条回答 默认 最新

  • douhui0975 2016-03-18 17:02
    关注

    The type you're passing into Unmarshal is not *J, you're passing in an *interface{}.

    When the json package reflects what the type is of the pointer it received, it sees interface{}, so it then uses the default types of the package to unmarshal into, which are

    bool, for JSON booleans
    float64, for JSON numbers
    string, for JSON strings
    []interface{}, for JSON arrays
    map[string]interface{}, for JSON objects
    nil for JSON null
    

    There is almost never a reason to use a pointer to an interface. If you find yourself using a pointer to an interface, and you don't know exactly why, then it's probably a mistake. If you want to unmarshal into J, then pass that in directly. If you need to assign that to an intermediary interface, make sure you use a pointer to the original value, not a pointer to its interface.

    http://play.golang.org/p/uJDFKfSIxN

    j := J{}
    var i interface{} = &j
    
    js := "{\"Text\": \"lala\"}"
    
    json.Unmarshal([]byte(js), i)
    
    fmt.Printf("%#v", i)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据