Search code examples
jsongomarshalling

JSON Marshal struct with method return as field


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?


Solution

  • 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)
    }