doubairan4213 2015-05-16 08:05
浏览 76
已采纳

编组类型时如何将方法结果嵌入JSON输出?

I'm seeking a clean approach to embed the return value of a method into the JSON marshalling of a type/value. It would be great if I don't need to write custom JSON marshaller.

For example, if the User type has FirstName and LastName fields and a FullName() method, how can I easily embed a full_name field into JSON output?

 type User struct {
     FirstName string `json:"first_name"`
     LastName  string `json:"last_name"`
 }

 func (u User) FullName() string {
     return fmt.Sprintf("%s %s", u.FirstName, u.LastName)
 }

Expected JSON:

 {
     "first_name": "John",
     "last_name":  "Smith",
     "full_name":  "John Smith"
 }
  • 写回答

3条回答 默认 最新

  • dsfdsf48652 2015-05-16 12:11
    关注

    This cannot be easily handled without providing some marshaller. I understand you don't want to write a MarshalJSON and do everything manually, but you can try to extend your structure in the custom marshaller and than rely on the default one. Proof of concept:

    type User struct {
        FirstName string `json:"first_name"`
        LastName  string `json:"last_name"`
    }
    
    func (u *User) FullName() string {
        return fmt.Sprintf("%s %s", u.FirstName, u.LastName)
    }
    
    func (u User) MarshalJSON() ([]byte, error) {
        type rawUser User // raw struct, without methods (and marshaller)       
        // Marshal rawUser with an extension
        return json.Marshal(struct {
            rawUser
            FullName string `json:"full_name"`
        }{rawUser(u), u.FullName()})
    }
    

    [play]

    You need to cast User to rawUser to strip all methods – otherwise you would have infinite loop of MarshalJSON. Also I've chosen MarshalJSON to operate on copy rather than pointer to make sure json.Marshal(user) will yield the same result as json.Marshal(&user).

    This is not a one liner, but hides the complexity behind a standard interface, so you don't need to remember there's a special, non-standard way of converting your structure to JSON.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题