JSON元帅结构,方法返回为字段 [英] JSON Marshal struct with method return as field

查看:48
本文介绍了JSON元帅结构,方法返回为字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用方法return作为字段来封送结构?例如,我想要这个JSON

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
}

具有这种结构

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 )

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) {
    value := 0
    for _, v := range d.Cards {
        value = value + v
    }

    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元帅结构,方法返回为字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆