繁体   English   中英

如何在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": {} 可能吗?

去游乐场获取完整代码: https//play.golang.org/p/tT15G2ESPVc

选项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


可能还有其他选择......

在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}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM