In Go, when facing the challenge of unmarshaling JSON data into an interface{}, it's essential to understand how to dynamically handle different data types based on specific keys. This article addresses this issue, providing a solution to unmarshal JSON into a generic interface{} in Go.
Consider a scenario where we have a type called Message with a struct that includes a Cmd field (string) and a Data field (interface{}). We also have a nested type CreateMessage that defines a specific data structure. When unmarshaling JSON data such as '{"cmd":"create","data":{"conf":{"a":1},"info":{"b":2}}}', we encounter an issue where the Data field is not properly converted to the appropriate CreateMessage type.
To address this problem, employ the following approach:
Here's an example code snippet that demonstrates the solution:
type Message struct { Cmd string `json:"cmd"` Data json.RawMessage } type CreateMessage struct { Conf map[string]int `json:"conf"` Info map[string]int `json:"info"` } func main() { var m Message if err := json.Unmarshal(data, &m); err != nil { log.Fatal(err) } switch m.Cmd { case "create": var cm CreateMessage if err := json.Unmarshal([]byte(m.Data), &cm); err != nil { log.Fatal(err) } fmt.Println(m.Cmd, cm.Conf, cm.Info) default: log.Fatal("bad command") } }
By leveraging this approach, JSON data can be dynamically unmarshaled into the appropriate data structures, enabling flexible handling of variant JSON data in Go.
The above is the detailed content of How Can I Dynamically Unmarshal JSON Data into Generic Types in Go?. For more information, please follow other related articles on the PHP Chinese website!