Home > Backend Development > Golang > How to Unmarshal JSON into Go Interfaces Based on a Dynamic Field Value?

How to Unmarshal JSON into Go Interfaces Based on a Dynamic Field Value?

Barbara Streisand
Release: 2024-12-21 20:01:11
Original
590 people have browsed it

How to Unmarshal JSON into Go Interfaces Based on a Dynamic Field Value?

Unmarshalling JSON into Interfaces in Go

Consider the scenario where you have a JSON string with varied data structures depending on a specific field, such as the "cmd" field. You want to unmarshal this JSON into a Go struct containing a field with an interface{} type and adapt it to different data structures based on the "cmd" value.

Solution

To achieve this, define a base struct with fixed fields and a json.RawMessage field to hold the variant data. Then, create specific struct types for each variant and unmarshal to them based on the command.

For example:

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

In this example, the Message struct represents the overall message structure, containing the "cmd" field and a json.RawMessage field to hold the variant data. CreateMessage is a specific struct type representing the "create" command variant.

The code unmarshals the initial JSON string into a Message variable and then uses the "cmd" field to determine which specific variant to unmarshal and print.

The above is the detailed content of How to Unmarshal JSON into Go Interfaces Based on a Dynamic Field Value?. 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