首页  >  文章  >  后端开发  >  以下是一些标题选项,请记住问题格式的需要: * **为什么 Go 中 `json.Unmarshal` 返回 Map 而不是结构体?**(简单直接) * **Golang:解组 int

以下是一些标题选项,请记住问题格式的需要: * **为什么 Go 中 `json.Unmarshal` 返回 Map 而不是结构体?**(简单直接) * **Golang:解组 int

DDD
DDD原创
2024-10-26 02:44:02325浏览

Here are a few title options, keeping in mind the need for a question format:

* **Why Does `json.Unmarshal` Return a Map Instead of a  Struct in Go?** (Simple and direct)
* **Golang: Unmarshaling into an Interface - Why is My Struct a Map?** (More specif

为什么 json.Unmarshal 返回一个映射而不是预期的结构?

在这个 Playground 示例中,json.Unmarshal 返回一个映射而不是预期的结构:http ://play.golang.org/p/dWku6SPqj5.

出现此问题的原因是,interface{} 参数被传递给 json.Unmarshal,并且库尝试将其解组为字节数组。然而,该库没有直接引用相应的结构体,尽管它有一个reflect.Type引用。

问题出在下面的代码中:

<code class="go">var ping interface{} = Ping{}
deserialize([]byte(`{"id":42}`), &ping)
fmt.Println("DONE:", ping) // It's a simple map now, not a Ping. Why?</code>

To解决此问题,要么将指针作为抽象接口显式传递给 Ping 结构:

<code class="go">var ping interface{} = &Ping{}
deserialize([]byte(`{"id":42}`), ping)
fmt.Println("DONE:", ping)</code>

或者,如果直接指针不可用,请使用反射创建一个新指针,反序列化到其中,然后复制返回值:

<code class="go">var ping interface{} = Ping{}
nptr := reflect.New(reflect.TypeOf(ping))
deserialize([]byte(`{"id":42}`), nptr.Interface())
ping = nptr.Interface()
fmt.Println("DONE:", ping)</code>

以上是以下是一些标题选项,请记住问题格式的需要: * **为什么 Go 中 `json.Unmarshal` 返回 Map 而不是结构体?**(简单直接) * **Golang:解组 int的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn