是否可以将方法返回作为字段封送结构?例如,我想要这个 JSON
{
"cards": [1,2,3],
"value": 6,
"size": 3
}
有了这种结构
type Deck struct {
Cards []int `json:"cards"`
Value func() int `json:"value"`
Size func() int `json:"size"`
}
Anyone?
您可以实施一个元帅 http://golang.org/pkg/encoding/json/#Marshaler像这样http://play.golang.org/p/ySUFcUOHCZ http://play.golang.org/p/ySUFcUOHCZ(或这个http://play.golang.org/p/ndwKu-7Y5m 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) {
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)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)