Home > Backend Development > Golang > Can Golang Use Multiple JSON Tags for a Single Struct Field?

Can Golang Use Multiple JSON Tags for a Single Struct Field?

Patricia Arquette
Release: 2024-12-13 03:48:10
Original
525 people have browsed it

Can Golang Use Multiple JSON Tags for a Single Struct Field?

JSON Tag Aliases in Golang

In Golang, the json struct tag is used to specify the JSON field name corresponding to a struct field. However, is it possible to assign multiple names to a single field?

The answer is yes, but not with the standard library's encoding/json package. To achieve this, you can utilize third-party JSON libraries such as github.com/json-iterator/go.

Using jsoniter

With jsoniter, you can define multiple JSON tags using the newtag property. Here's an example:

package main

import (
    "fmt"
    "github.com/json-iterator/go"
)

type TestJson struct {
    Name string `json:"name" newtag:"newname"`
    Age  int    `json:"age" newtag:"newage"`
}

func main() {
    var json = jsoniter.ConfigCompatibleWithStandardLibrary
    data := TestJson{}
    data.Name = "zhangsan"
    data.Age = 22
    byt, _ := json.Marshal(&data)
    fmt.Println(string(byt)) // {"name":"zhangsan","age":22}

    var newJson = jsoniter.Config{
        TagKey: "newtag",
    }.Froze()

    byt, _ = newJson.Marshal(&data)
    fmt.Println(string(byt)) // {"newname":"zhangsan","newage":22}
}
Copy after login

In this example, the TestJson struct defines multiple JSON tags for the Name and Age fields. When serializing using the standard library's json package, it uses the default json tag. However, when using jsoniter with the newtag configuration, it uses the specified newtag values instead.

The above is the detailed content of Can Golang Use Multiple JSON Tags for a Single 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