Is it possible to marshal a struct with method return as field? For example, I want this JSON
{
"cards": [1,2,3],
"value": 6,
"size": 3
}
With this kind of struct
type Deck struct {
Cards []int `json:"cards"`
Value func() int `json:"value"`
Size func() int `json:"size"`
}
Anyone?
You can implement a Marshaler like this http://play.golang.org/p/ySUFcUOHCZ (or this 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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With