实现JSON Marshaler接口时获取标签。

huangapple go评论75阅读模式
英文:

Get tag when implementing JSON Marshaler interface

问题

在实现JSON marshaler接口时,当对下面的Foo实例进行编组时,我们如何获取标签信息?请注意,我们还可以有一个Bar结构体,它也使用了MyNullString。因此,我们不能假设MyNullString仅被Foo结构体使用。

package main

import (
    "fmt"
    "database/sql"
    "encoding/json"
)

type MyNullString struct {
    sql.NullString
}

type Foo struct {
    MyInt    int64        // MyInt字段
    MyString MyNullString `json:"my_string,omitempty"` // MyString字段
}

func (s *MyNullString) MarshalJSON() ([]byte, error) {
    // 检查结构体实例的标签,看看当为空时是否应该省略该字段
    // 如何实现????
    // 注意:我们也可以在其他结构体中使用MyNullString。
}

func main() {
    foo := Foo{MyInt: 1}
    data, _ := json.Marshal(&foo)
    fmt.Println(string(data))
}

以上是要翻译的内容。

英文:

How do we get the tag information when implementing the JSON marshaler interface when marshaling the Foo instance below? Note that we can also have a Bar struct which also uses MyNullString. So we cannot assume MyNullString is being used only by Foo struct.

package main

import (
  "fmt"
  "database/sql"
  "encoding/json"
)
type MyNullString struct {
   sql.NullString
}

type Foo struct {
    MyInt int64
    MyString MyNullString `json:"my_string,omitempty"` 
}

func (s *MyNullString) MarshalJSON() ([]byte, error){
    //Inspect tag of struct instance and see if this field has to be omitted when empty
    //HOW?????
    //Note: We can use MyNullString in other structs as well. 
}

func main(){
   foo := Foo{MyInt: 1}
   data, _ := json.Marshal(&foo)
   fmt.Println(string(data))
}

答案1

得分: 0

一个类型无法检查包含它的其他类型/值(你无法看到你所在的盒子,但你可以看到你内部的盒子)。目前有一个关于自定义omitempty支持的开放功能请求,以便类型可以通知编码器它是一个“空”值,但目前还没有可用的解决方案。请参阅http://golang.org/issue/4357。

英文:

It's not possible for a type to inspect other types/values that contain it (you can't see the box you're in, but you can see the boxes in you). There is an open feature request for custom omitempty support, such that a type can inform the encoder that it's an "empty" value, but there's nothing usable at this time. See http://golang.org/issue/4357

huangapple
  • 本文由 发表于 2014年5月26日 02:31:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/23858606.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定