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} }
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!