如何在 Go json marshal 中显示空对象而不是空结构或 nil

How to show empty object instead of empty struct or nil in Go json marshal

我需要在为结构指针执行 json.Marshal() 时显示 json 的空对象 {}。我只能输出 null 值或空结构值。

如果 person 键被 &Person{}new(Person) 填充,它将显示如下空结构:

{
    "data": {
        "person": {
            "name": "",
            "age": 0
        },
        "created_date": "2009-11-10T23:00:00Z"
    }
}

如果我们根本不初始化它,它会显示null

{
    "data": {
        "person": null,
        "created_date": "2009-11-10T23:00:00Z"
    }
}

我要展示"person": {}。可能吗?

前往 Playground 获取完整代码:https://play.golang.org/p/tT15G2ESPVc

在 Go 中,根据定义,空结构将零值分配给字段元素。例如:对于 int 0,“”对于字符串等

对于您的情况,只需与 null 进行比较即可。或者,您可以将 emptyPerson 定义为:

 var BAD_AGE = -1
 emptyPerson := &Person{"", BAD_AGE} // BAD_AGE indicates no person
 if person[age] == BAD_AGE {
    // handle case for emptyPerson}

选项 A,在所有 Person 的字段上使用 omitempty 标记选项,并确保在封送处理之前分配响应的字段。

type Person struct {
    Name string `json:"name,omitempty"`
    Age  int    `json:"age,omitempty"`
}

// ...

resp.Person = new(Person)

https://play.golang.org/p/o3jWdru_8bC


选项B,使用嵌入Person指针类型的非指针包装器类型。

type PersonJSON struct {
    *Person
}

type Response struct {
    Person      PersonJSON `json:"person"`
    CreatedDate time.Time   `json:"created_date"`
}

https://play.golang.org/p/EKQc7uf1_Vk


选项 C,让 Reponse 类型实现 json.Marshaler 接口。

func (r *Response) MarshalJSON() ([]byte, error) {
    type tmp Response
    resp := (*tmp)(r)

    var data struct {
        Wrapper struct {
            *Person
        } `json:"person"`
        *tmp
    }
    data.Wrapper.Person = resp.Person
    data.tmp = resp
    return json.Marshal(data)
}

https://play.golang.org/p/1qkSCWZ225j


可能还有其他选择...