Golang multiple json tag names for one field

后端 未结 2 1117
感情败类
感情败类 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:37

    See How to define multiple name tags in a struct on how you can define multiple tags on one struct field.

    You can also use a type Info map[string]interface{} instead of your struct.

    Or you can use both types in your structure, and make method Details() which will return right pattern.

    type Animation struct {
        Name    string  `json:"name"`
        Repeat  int     `json:"repeat"`
        Speed   uint    `json:"speed"`
        Pattern Pattern `json:"pattern"`
        Frame   Pattern `json:"frames"`
    }
    
    func (a Animation) Details() Pattern {
        if a.Pattern == nil {
            return a.Frame
        }
        return a.Pattern
    }
    

提交回复
热议问题