How can I include the result of a method call when exporting to JSON using Go?

huangapple go评论128阅读模式
英文:

How can I include the result of a method call when exporting to JSON using Go?

问题

请稍等,我会为您翻译以下内容:

假设有以下代码:

  1. type Ninja struct {
  2. name string
  3. }
  4. func (n *Ninja) Shurikens() int {
  5. return 2
  6. }
  7. n := &Ninja{"超级忍者"}

我想将其序列化为JSON,并获得以下结果:

  1. {"Name": "超级忍者", "Shurikens": 2}

这只是我需要的简化版本(在结构体上调用方法,并将该输出包含在生成的JSON中)。

英文:

Imagine the following:

  1. type Ninja struct {
  2. name string
  3. }
  4. func (n *Ninja) Shurikens() int {
  5. return 2
  6. }
  7. n := &Ninja{"Super Ninja"}

I'd like to serialize this to JSON, and obtain the following:

  1. {'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方法,像这样:

  1. func (n *Ninja) MarshalJSON() ([]byte, error) {
  2. return []byte(fmt.Sprintf(`{"Name":"%s", "Shurikens":%d}`, n.name, n.Shurikens())), nil
  3. }
  4. func main() {
  5. n := []*Ninja{{"X"}, {"Y"}}
  6. b, err := json.Marshal(n)
  7. fmt.Println(string(b), err)
  8. }

请注意,你的name字段没有导出,因为它不以大写字母开头,所以你将无法对结构体进行反序列化。

英文:

Short answer, you can't, your Shurikens has to be a field.

Long answer, well, you can use a custom MarshalJSON like this:

  1. func (n *Ninja) MarshalJSON() ([]byte, error) {
  2. return []byte(fmt.Sprintf(`{"Name":"%s", "Shurikens":%d}`, n.name, n.Shurikens())), nil
  3. }
  4. func main() {
  5. n := []*Ninja{{"X"}, {"Y"}}
  6. b, err := json.Marshal(n)
  7. fmt.Println(string(b), err)
  8. }

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.

huangapple
  • 本文由 发表于 2014年7月2日 22:24:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/24533690.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定