Golang multiple json tag names for one field

陌路散爱 提交于 2019-12-22 04:27:30

问题


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"`
}

回答1:


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
}



回答2:


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}


来源:https://stackoverflow.com/questions/38809137/golang-multiple-json-tag-names-for-one-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!