XML and JSON tags for a Golang struct?

2019-03-14 08:49发布

问题:

I have an application that can output as JSON or XML depending on the HTTP request headers. I can achieve the correct output for either by adding the correct tags to the structs I'm using, but I can't figure out how to specify the tags for both JSON and XML.

For example, this serializes to correct XML:

type Foo struct {
    Id          int64       `xml:"id,attr"`
    Version     int16       `xml:"version,attr"`
}

...and this generates correct JSON:

type Foo struct {
    Id          int64       `json:"id"`
    Version     int16       `json:"version"`
}

...but this doesn't work for either:

type Foo struct {
    Id          int64       `xml:"id,attr",json:"id"`
    Version     int16       `xml:"version,attr",json:"version"`
}

回答1:

Go tags are space-separated. From the manual:

By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.

So, what you want to write is:

type Foo struct {
    Id          int64       `xml:"id,attr" json:"id"`
    Version     int16       `xml:"version,attr" json:"version"`
}