英文:
How can I include the result of a method call when exporting to JSON using Go?
问题
请稍等,我会为您翻译以下内容:
假设有以下代码:
type Ninja struct {
name string
}
func (n *Ninja) Shurikens() int {
return 2
}
n := &Ninja{"超级忍者"}
我想将其序列化为JSON,并获得以下结果:
{"Name": "超级忍者", "Shurikens": 2}
这只是我需要的简化版本(在结构体上调用方法,并将该输出包含在生成的JSON中)。
英文:
Imagine the following:
type Ninja struct {
name string
}
func (n *Ninja) Shurikens() int {
return 2
}
n := &Ninja{"Super Ninja"}
I'd like to serialize this to JSON, and obtain the following:
{'Name': 'Super Ninja', 'Shurikens':2}
It's just a simplification of what I need ( calling methods on structs, and including that output in the resulting JSON ).
答案1
得分: 5
简短回答,你不能这样做,你的Shurikens
字段必须是一个可导出的字段。
详细回答,你可以使用自定义的MarshalJSON
方法,像这样:
func (n *Ninja) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`{"Name":"%s", "Shurikens":%d}`, n.name, n.Shurikens())), nil
}
func main() {
n := []*Ninja{{"X"}, {"Y"}}
b, err := json.Marshal(n)
fmt.Println(string(b), err)
}
请注意,你的name
字段没有导出,因为它不以大写字母开头,所以你将无法对结构体进行反序列化。
英文:
Short answer, you can't, your Shurikens
has to be a field.
Long answer, well, you can use a custom MarshalJSON
like this:
func (n *Ninja) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`{"Name":"%s", "Shurikens":%d}`, n.name, n.Shurikens())), nil
}
func main() {
n := []*Ninja{{"X"}, {"Y"}}
b, err := json.Marshal(n)
fmt.Println(string(b), err)
}
Keep in mind that your name
field isn't exported since it doesn't start with a capital letter, so you will not be able to Unmarshal your struct.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论