Golang multiple json tag names for one field

后端 未结 2 1119
感情败类
感情败类 2021-02-19 15:00

It it possible in Golang to use more than one name for a JSON struct tag ?

type Animation struct {
    Name    string  `json:\"name\"`
    Repeat  int     `json:         


        
2条回答
  •  北海茫月
    2021-02-19 15:48

    you can use multiple json tag with third part json lib like github.com/json-iterator/go coding like below:

    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))
    
        var NewJson = jsoniter.Config{
            EscapeHTML:             true,
            SortMapKeys:            true,
            ValidateJsonRawMessage: true,
            TagKey:                 "newtag",
        }.Froze()
    
        byt, _ = NewJson.Marshal(&data)
        fmt.Println(string(byt))
    }
    
    output:
    
        {"name":"zhangsan","age":22}
        {"newname":"zhangsan","newage":22}
    

提交回复
热议问题