Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 409
Yanc0 Avatar asked Aug 06 '15 06:08

Yanc0


1 Answers

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)
}
like image 77
J-16 SDiZ Avatar answered Oct 08 '22 14:10

J-16 SDiZ