JSON元帅结构,方法返回为字段

Yan*_*nc0 6 json marshalling go

是否可以使用方法return作为字段来封送结构?例如,我想要这个JSON

{
  "cards": [1,2,3],
  "value": 6,
  "size": 3
}
Run Code Online (Sandbox Code Playgroud)

有了这种结构

type Deck struct {
   Cards []int    `json:"cards"`
   Value func() int `json:"value"`
   Size  func() int `json:"size"`
}
Run Code Online (Sandbox Code Playgroud)

任何人?

J-1*_*DiZ 7

您可以实现封送这样http://play.golang.org/p/ySUFcUOHCZ (或本http://play.golang.org/p/ndwKu-7Y5m

package main

import "fmt"
import "encoding/json"

type Deck struct {
    Cards []int
}

func (d Deck) Value() int {
    value := 0
    for _, v := range d.Cards {
        value = value + v
    }
    return value
}
func (d Deck) Size() int {
    return len(d.Cards)
}

func (d Deck) MarshalJSON() ([]byte, error) {
    value := 0
    for _, v := range d.Cards {
        value = value + v
    }

    return json.Marshal(struct {
        Cards []int `json:"cards"`
        Value int   `json:"value"`
        Size  int   `json:"size"`
    }{
        Cards: d.Cards,
        Value: d.Value(),
        Size:  d.Size(),
    })
}

func main() {
    deck := Deck{
        Cards: []int{1, 2, 3},
    }

    b, r := json.Marshal(deck)
    fmt.Println(string(b))
    fmt.Println(r)
}
Run Code Online (Sandbox Code Playgroud)