Golang tag names for multiple json fields for one field

Can Golang use more than one name for a JSON structure tag?

type Animation struct {
    Name    string  `json:"name"`
    Repeat  int     `json:"repeat"`
    Speed   uint    `json:"speed"`
    Pattern Pattern `json:"pattern",json:"frames"`
}
+8
source share
2 answers

EDIT: This answer is not correct. See Zhang's answer for the correct answer, or see how to define multiple name tags in a structure .

It is not allowed to have more than one tag for one field. When such functionality is required, you can use type Info map[string]interface{}instead of your structure.

Or you can use both types in your structure and create a method Details()that will return the correct template.

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
}
+9

json json lib, , github.com/json-iterator/go github.com/json-iterator/go :

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}
+3

Source: https://habr.com/ru/post/1650427/


All Articles