Home > Article > Backend Development > How to Unmarshal JSON into a Specific Struct Using an Interface Variable in Go?
How to Unmarshal JSON into a Specific Struct Using Interface Variables
Problem:
When unmarshaling JSON into an interface variable, the encoding/json package interprets it as a map. How can we instruct it to use a specific struct instead?
Explanation:
The JSON package requires a concrete type to target when unmarshaling. Passing an interface{} variable doesn't provide sufficient information, and the package defaults to map[string]interface{} for objects and []interface{} for arrays.
Solution:
There is no built-in way to tell json.Unmarshal to unmarshal into a concrete struct type using an interface variable. However, there is a workaround:
func getFoo() interface{} { return &Foo{"bar"} }
err := json.Unmarshal(jsonBytes, fooInterface)
fmt.Printf("%T %+v", fooInterface, fooInterface)
Example:
The following code demonstrates the technique:
package main import ( "encoding/json" "fmt" ) type Foo struct { Bar string `json:"bar"` } 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) // prints: *main.Foo &{Bar:This is the new value of bar} }
The above is the detailed content of How to Unmarshal JSON into a Specific Struct Using an Interface Variable in Go?. For more information, please follow other related articles on the PHP Chinese website!