该
encoding/json包不能奇迹般地猜测你想要的结果取消封送进去,除非你告诉它什么类型。
告诉要取消的内容的一种方法是将该类型的值传递给
json.Unmarshal()函数。
不幸的是,没有其他办法。如果您传递
interface{}类型的值,则json包实现可以自由选择其选择的类型,它将
map[string]interface{}为JSON对象和[]interface{}JSON数组选择。记录在json.Unmarshal():
要将JSON解组为接口值,Unmarshal将其中之一存储在接口值中:
bool, for JSON booleansfloat64, for JSON numbersstring, for JSON strings[]interface{}, for JSON arraysmap[string]interface{}, for JSON objectsnil for JSON null
如果您事先知道类型,请创建该类型的值,然后传递该值以进行编组。是否
interface{}事先将其存储在变量中无关紧要;如果传递的值适合解组,则将使用它。请注意,传递的值将被包装为,interface{}如果尚未包含,则为,因为这是的参数类型json.Unmarshal()。
代码失败的原因是因为您传递了一个
*interface{}包装非指针Foo值的type
值。由于
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}


