我可以使用MarshalJSON将任意字段添加到golang中的json编码吗? [英] Can I use MarshalJSON to add arbitrary fields to a json encoding in golang?

查看:393
本文介绍了我可以使用MarshalJSON将任意字段添加到golang中的json编码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我写了下面的代码片段。操场上的完整代码此处适合那些倾向。

  type Book struct {
标题字符串
作者字符串
}

func main(){
ms:= Book {Catch-22,Joseph Heller}
out,err:= json.MarshalIndent(ms,,)
if err!= nil {
log.Fatalln(err)
}
fmt.Println(string(out))
}

此代码输出以下内容,完全如我所料:

  {
Title:Catch-22,
作者:Joseph Heller
}

假设我想在JSON输出中添加一个字段,而不将它包含在 Book struct中。可能是一种流派:

  {
Title:Catch-22,
Author :Joseph Heller,
Genre:Satire
}

我可以使用 MarshalJSON()将任意字段添加到 Marshal()上的JSON负载。例如:

  func(b * Book)MarshalJSON()([] byte,error){
//一些代码
}

其他让我觉得这应该是可能的,但我正在努力弄清楚实施。

这里比我以前的答案更好。



<$ p $ (


func(b Book)MarshalJSON()([] byte,error){
return json.Marshal(struct {
FakeBook
类型字符串
} {
FakeBook:FakeBook(b),
类型:讽刺,
})
}

由于匿名结构字段是合并的(有一些额外的考虑),我们可以使用它来避免重新映射单个字段。请注意使用 FakeBook 类型来避免无限递归,否则会发生。



Playground: http://play.golang.org/p/21YXhB6OyC


Suppose I've written the following code snippet. Full code on the playground here for those inclined.

type Book struct {
  Title        string
  Author       string
}

func main() {
  ms := Book{"Catch-22", "Joseph Heller"}
  out, err := json.MarshalIndent(ms, "", "  ")
  if err != nil {
    log.Fatalln(err)
  }
  fmt.Println(string(out))
}

This code outputs the following, exactly as I'd expect:

{
  "Title": "Catch-22",
  "Author": "Joseph Heller"
}

Suppose for a moment I wanted to add a field to the JSON output without including it in the Book struct. Perhaps a genre:

{
  "Title": "Catch-22",
  "Author": "Joseph Heller",
  "Genre": "Satire"
}

Can I use MarshalJSON() to add an arbitrary field to the JSON payload on Marshal()? Something like:

func (b *Book) MarshalJSON() ([]byte, error) {
    // some code
}

Other answers make me think this should be possible, but I'm struggling to figure out the implementation.

解决方案

Here's a better answer than my previous one.

type FakeBook Book

func (b Book) MarshalJSON() ([]byte, error) {
    return json.Marshal(struct {
        FakeBook
        Genre string
    }{
        FakeBook: FakeBook(b),
        Genre:    "Satire",
    })
}

Since anonymous struct fields are "merged" (with a few additional considerations) we can use that to avoid remapping the individual fields. Note the use of the FakeBook type to avoid the infinite recursion which would otherwise occur.

Playground: http://play.golang.org/p/21YXhB6OyC

这篇关于我可以使用MarshalJSON将任意字段添加到golang中的json编码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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