英文:
How to tell json.Unmarshal to use struct instead of interface
问题
我想编写一个函数,可以接收多种类型的结构体,并将它们从JSON解组。为此,我有另一组具有预定义签名的函数,它们返回结构体实例,但由于每个函数返回不同类型的结构体,函数签名的返回类型是interface{}
。
当我将具体的结构体发送给json.Unmarshal时,它按照我预期的方式工作,但当我将相同的结构体作为interface{}
发送时,它会将其转换为映射。
这里是一个简化的示例代码,描述了这个问题:
package main
import (
"encoding/json"
"fmt"
)
type Foo struct {
Bar string `json:"bar"`
}
func getFoo() interface{} {
return Foo{"bar"}
}
func main() {
fooInterface := getFoo()
fooStruct := Foo{"bar"}
fmt.Println(fooInterface) //{bar}
fmt.Println(fooStruct) //{bar}
myJSON := `{"bar":"This is the new value of bar"}`
jsonBytes := []byte(myJSON)
err := json.Unmarshal(jsonBytes, &fooInterface)
if err != nil {
fmt.Println(err)
}
fmt.Println(fooInterface) //map[bar:This is the new value of bar]
err = json.Unmarshal(jsonBytes, &fooStruct)
if err != nil {
fmt.Println(err)
}
fmt.Println(fooStruct) //{This is the new value of bar}
}
我期望json.Unmarshal使用接口背后的具体结构体进行解组,但它并没有这样做,而是将值的映射分配给传递的接口。
为什么它不使用具体的结构体,并且有没有一种方法可以告诉它使用具体的结构体类型,而不需要显式转换(我在设计时不知道具体的类型)?
英文:
I want to write a function that receives several types of structs and unmarshals them from JSON. To this end, I have another set of functions with a pre-defined signature that return the struct instances but since each function returns a different type of struct the function signature has interface{}
as the return type.
When I send json.Unmarshal a concrete struct it works as I expected but when I send the same struct as interface{}
it converts it to a map.
Here is a simplified example code that depicts the problem:
package main
import (
"encoding/json"
"fmt"
)
type Foo struct {
Bar string `json:"bar"`
}
func getFoo() interface{} {
return Foo{"bar"}
}
func main() {
fooInterface := getFoo()
fooStruct := Foo{"bar"}
fmt.Println(fooInterface) //{bar}
fmt.Println(fooStruct) //{bar}
myJSON := `{"bar":"This is the new value of bar"}`
jsonBytes := []byte(myJSON)
err := json.Unmarshal(jsonBytes, &fooInterface )
if err != nil {
fmt.Println(err)
}
fmt.Println(fooInterface) //map[bar:This is the new value of bar]
err = json.Unmarshal(jsonBytes, &fooStruct)
if err != nil {
fmt.Println(err)
}
fmt.Println(fooStruct) //{This is the new value of bar}
}
https://play.golang.org/p/tOO7Ki_i4c
I expected json.Unmarshal to use the concrete struct behind the interface for unmarshaling but it doesn't and just assigns the map of values to the passed interface.
Why doesn't it use the concrete struct and is there a way to tell it to use the concrete struct type without explicit casting (I don't know the explicit type at design time)?
答案1
得分: 10
encoding/json
包无法自动猜测您希望将结果解组为的类型,除非您告诉它。
告诉解组函数要解组成什么类型的一种方法是将该类型的值传递给 json.Unmarshal()
函数。
不幸的是,没有其他方法。如果您传递的是 interface{}
类型的值,json
包的实现将自由选择一种类型,并选择 map[string]interface{}
作为 JSON 对象的类型,选择 []interface{}
作为 JSON 数组的类型。这在 json.Unmarshal()
中有记录:
> 要将 JSON 解组为接口值,Unmarshal 将以下之一存储在接口值中:
>
> bool,用于 JSON 布尔值
> float64,用于 JSON 数字
> string,用于 JSON 字符串
> []interface{},用于 JSON 数组
> map[string]interface{},用于 JSON 对象
> nil,用于 JSON null
如果您事先知道类型,请创建该类型的值,并将其传递给解组函数。事先将其存储在 interface{}
变量中并不重要;如果传递的值适合解组,它将被使用。请注意,如果传递的值尚未是 interface{}
类型,它将被包装在 interface{}
中,因为这是 json.Unmarshal()
的参数类型。
您的代码失败的原因是您传递了一个类型为 *interface{}
的值,它包装了一个非指针的 Foo
值。由于 json
包无法使用这个值,它会创建一个自己选择的新值(一个映射)。
相反,您应该将 *Foo
值包装在一个 interface{}
中,并将其传递给解组函数:
func getFoo() interface{} {
return &Foo{"bar"}
}
func main() {
fooInterface := getFoo()
myJSON := `{"bar":"This is the new value of bar"}`
jsonBytes := []byte(myJSON)
err := json.Unmarshal(jsonBytes, fooInterface)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%T %+v", fooInterface, fooInterface)
}
这将得到以下结果(在 Go Playground 上尝试):
*main.Foo &{Bar:This is the new value of bar}
英文:
The encoding/json
package can't magically guess what type you want the result unmarshaled into, unless you tell it to.
One way of telling what to unmarsal into is to pass value of that type to the json.Unmarshal()
function.
And unfortunately there is no other way. If you pass a value of interface{}
type, the json
package implementation is free to choose a type of its choice, and it will choose map[string]interface{}
for JSON objects, and []interface{}
for JSON arrays. This is documented at json.Unmarshal()
:
> To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:
>
> 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
If you know the type beforehand, create a value of that type, and pass that for unmarshaling. Whether your store this in an interface{}
variable beforehand does not matter; if the passed value is suitable for unmarshaling, it will be used. Note that the passed value will be wrapped in an interface{}
if not already of that type, as that is the parameter type of json.Unmarshal()
.
The problem why your code fails is because you pass a value of type *interface{}
which wraps a non-pointer Foo
value. Since the json
package can't use this, it creates a new value of its choice (a map).
Instead you should wrap a *Foo
value in an interface{}
, and pass that:
func getFoo() interface{} {
return &Foo{"bar"}
}
func main() {
fooInterface := getFoo()
myJSON := `{"bar":"This is the new value of bar"}`
jsonBytes := []byte(myJSON)
err := json.Unmarshal(jsonBytes, fooInterface)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%T %+v", fooInterface, fooInterface)
}
This results in (try it on the Go Playground):
*main.Foo &{Bar:This is the new value of bar}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论