我正在从外部来源获取 JSON 数据。这个 JSON 中的字段名称不是我想随身携带的东西,所以我使用 json:"originalname"
标签将它们转换为对我有意义的名称。
当我将这样的对象编码回 JSON 时,我自然会再次获得丑陋的(原始)名称。
有没有办法在编码时忽略标签?或者为 marshall 和 unmarshall 指定不同名称的方法?
为了澄清,我准备了一个 example in the playground 并在下面粘贴了相同的代码。
提前致谢。
package main
import (
"encoding/json"
"fmt"
)
type Band struct {
Name string `json:"bandname"`
Albums int `json:"albumcount"`
}
func main() {
// JSON -> Object
data := []byte(`{"bandname": "AC/DC","albumcount": 10}`)
band := &Band{}
json.Unmarshal(data, band)
// Object -> JSON
str, _ := json.Marshal(band)
fmt.Println("Actual Result: ", string(str))
fmt.Println("Desired Result:", `{"Name": "AC/DC","Albums": 10}`)
// Output:
// Actual Result: {"bandname":"AC/DC","albumcount":10}
// Desired Result: {"Name": "AC/DC","Albums": 10}
}
最佳答案
你可以实现
type Marshaler interface {
MarshalJSON() ([]byte, error)
}
来自标准库的
encoding/json
包。例子:type Band struct {
Name string `json:"bandname"`
Albums int `json:"albumcount"`
}
func (b Band) MarshalJSON() ([]byte, error) {
n, _ := json.Marshal(b.Name)
a, _ := json.Marshal(b.Albums)
return []byte(`{"Name":` + string(n) + `,"Albums":` + string(a) + `}`)
}
诚然,这不是一个很好的解决方案。
关于json - 编码时忽略 JSON 标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26426746/