是否可以使用方法返回作为字段来编码结构?例如,我想要这个 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"`
}
有人吗?
最佳答案
您可以实现 Marshaler像这样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) {
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)
}
关于方法返回为字段的 JSON Marshal 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31848836/