Home > Backend Development > Golang > How Can I Dynamically Unmarshal JSON Data into Generic Types in Go?

How Can I Dynamically Unmarshal JSON Data into Generic Types in Go?

Linda Hamilton
Release: 2024-12-17 20:09:11
Original
136 people have browsed it

How Can I Dynamically Unmarshal JSON Data into Generic Types in Go?

Utilizing Generic Types in JSON Unmarshaling with Go

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.

The Problem

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.

The Solution

To address this problem, employ the following approach:

  • Define a type Message with a Data field of type json.RawMessage to capture the variant portion of the message.
  • Create struct types for each of the different data structures, such as CreateMessage, and unmarshal the Data into them based on the Cmd value.

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")
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template