方法返回为字段的 JSON Marshal 结构

标签 json go marshalling

是否可以使用方法返回作为字段来编码结构?例如,我想要这个 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/

相关文章:

python - 如何使用python恢复文件的读取操作

python - 将 Python Thrift 客户端与 Go gRPC 服务器接口(interface)

c# - 将 float[] 作为 ref float 传递给非托管代码是个好主意吗?

c# - 通过 COM 接口(interface)时出错

string - "count"字符串的结果 "pattern"没有得到打印。这是代码

c# - 将 C 结构编码为 C# 委托(delegate)的返回值

javascript - MVC3 Ajax ActionLink 在使用 TempData 完成时调用 javascript 函数

json unmarshal 不工作但解码确实

php - 在 MySQL 中转换 PHP json_encode UTF8 十六进制实体

concurrency - 为什么我不能在函数参数中使用 type []chan *Message as type []chan interface{}?