doushangan3690
2016-08-06 22:07
浏览 1.4k

Golang在一个字段中使用多个json标记名称[重复]

This question already has an answer here:

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:"repeat"`
    Speed   uint    `json:"speed"`
    Pattern Pattern `json:"pattern",json:"frames"`
}
</div>

图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 在这里有答案

  • 如何在结构中定义多个名称标签 2个答案

    在Golang中,一个名称可能会使用多个名称 JSON结构标记?

      type动画结构{
    名称字符串`json:“ name”`
    重复int`json:“ repeat”`
     Speed uint`json  :“ speed”`
    模式模式`json:“ pattern”,json:“ frames”`
    } 
       
     
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douke1905 2016-08-06 22:24
    已采纳

    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
    }
    
    已采纳该答案
    打赏 评论
  • dpzp5127 2018-06-21 10:42

    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}
    
    打赏 评论

相关推荐 更多相似问题