Home > Backend Development > Golang > Can Multiple JSON Tags Be Defined for a Single Go Struct Field?

Can Multiple JSON Tags Be Defined for a Single Go Struct Field?

Susan Sarandon
Release: 2024-12-24 14:27:18
Original
752 people have browsed it

Can Multiple JSON Tags Be Defined for a Single Go Struct Field?

Struct with Multiple JSON Tags

In a scenario where a JSON response is received from a server and needs to be unmarshaled into a struct, there might be a requirement to modify the JSON tags before sending it to another server. Typically, this would involve creating a new struct and manually copying data over.

However, it's worth considering whether it's possible to define multiple JSON tags for a single struct. Attempting to attach multiple tags to the same field directly in the struct definition, as in the example below, is not supported:

type Foo struct {
    Name string `json:"name" json:"employee_name"`
    Age  int    `json:"age" json:"-"`
}
Copy after login

Instead, a possible solution lies in casting between two identically laid out structs (matching names, types, and field ordering). While this approach is generally discouraged, it can be employed cautiously to achieve the desired result.

type Foo struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

type Bar struct {
    Name string `json:"employee_name"`
    // Age is not exported
    age int `json:"-"`
}

func main() {
    foo := Foo{}
    // Unmarshal JSON
    err := json.Unmarshal([]byte("{\"name\":\"Sam\",\"age\":20}"), &foo)
    if err != nil {
        log.Fatal(err)
    }

    // Cast between types, overwriting internal representation
    bar := (*Bar)(unsafe.Pointer(&foo))

    // Marshal modified JSON
    data, err := json.Marshal(bar)
    if err != nil {
        log.Fatal(err)
    }

    // Example JSON: {"employee_name":"Sam"}
    fmt.Println(string(data))
}
Copy after login

It's important to note that this casting approach should be used judiciously. The second struct should be unexported to prevent unintended usage outside of the specific context.

The above is the detailed content of Can Multiple JSON Tags Be Defined for a Single Go Struct Field?. 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