Go json 能否解码到一个 interface 类型的值

简介: Go json 能否解码到一个 interface 类型的值

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站

通过代码描述一下这里的具体操作:

type Parent interface {
  Test()
}
type Child struct {
  Name string `json:"name"`
}
func (c Child) Test() {
}
func createChild() Parent {
  return Child{}
}
func test() Parent {
    // c 是一个 Parent 类型
  c := createChild()
  s := `{"name":"123"}`
  err := json.Unmarshal([]byte(s), &c)
    if err != nil {
        panic(err)
    }
    // 问题:这里能不能得到 name 的值 123?
  fmt.Printf("name=%s\n", c.(Child).Name)
  return c
}

答案:不行

问题描述

具体就是,我有一个结构体 Child 实现了接口 Parent,然后 Child 里面有 name 属性,然后在反序列化的时候,用指向 Parent,类型的值来接收。

结果就是,结构体里面字段都丢失了。

如果我们写成下面这样,就可能错过了发现错误的机会(我一开始就是这么写的):

_ = json.Unmarshal([]byte(s), &c)

如果打印错误的话,其实编译器已经给出了明确的报错信息:

panic: json: cannot unmarshal object into Go value of type body.Parent [recovered]
  panic: json: cannot unmarshal object into Go value of type body.Parent

原因

在反序列化的时候,反射处理是拿不到那个值的具体类型的。

参考链接:https://stackoverflow.com/questions/32428797/unmarshal-to-a-interface-type

原答案:

You can marshal from an interface type variable, because the object exists locally, so the reflector knows the underlying type.

You cannot unmarshal to an interface type, because the reflector does not know which concrete type to give to a new instance to receive the marshaled data.


目录
相关文章
|
2月前
|
JSON 安全 前端开发
类型安全的 Go HTTP 请求
类型安全的 Go HTTP 请求
|
10天前
|
XML JSON 数据可视化
数据集学习笔记(二): 转换不同类型的数据集用于模型训练(XML、VOC、YOLO、COCO、JSON、PNG)
本文详细介绍了不同数据集格式之间的转换方法,包括YOLO、VOC、COCO、JSON、TXT和PNG等格式,以及如何可视化验证数据集。
13 1
数据集学习笔记(二): 转换不同类型的数据集用于模型训练(XML、VOC、YOLO、COCO、JSON、PNG)
|
1月前
|
存储 Go
Go: struct 结构体类型和指针【学习笔记记录】
本文是Go语言中struct结构体类型和指针的学习笔记,包括结构体的定义、成员访问、使用匿名字段,以及指针变量的声明使用、指针数组定义使用和函数传参修改值的方法。
|
2月前
|
人工智能 JSON NoSQL
Go MongoDB Driver 中的 A D M E 类型是什么
Go MongoDB Driver 中的 A D M E 类型是什么
35 1
|
2月前
|
安全 Go
|
2月前
|
存储 安全 程序员
|
2月前
|
编译器 Go 开发者
Go 在编译时评估隐式类型的优点详解
【8月更文挑战第31天】
28 0
|
2月前
|
存储 编译器 Go
|
2月前
|
存储 安全 Go
深入理解 Go 语言中的指针类型
【8月更文挑战第31天】
29 0
|
2月前
|
JSON Go 数据格式
Go实现json字符串与各类struct相互转换
文章通过Go语言示例代码详细演示了如何实现JSON字符串与各类struct之间的相互转换,包括结构体对象生成JSON字符串和JSON字符串映射到struct对象的过程。
21 0