gpt4 book ai didi

arrays - 使用 struct 在 Go 中处理空 JSON 数组

转载 作者:行者123 更新时间:2023-12-05 02:38:21 25 4
gpt4 key购买 nike

在 golang 中追加结构后,我们有结构并得到空值。在下面的结构中找到我在 golang 中的部分代码。

type XmloutRoomRate struct {    
CancellationPolicy Policies `bson:"cancellationPolicy" json:"cancellationPolicy"`
}


type Policies struct {
Policies []RoomPolicies `bson:"policies" json:"policies"`
}


type RoomPolicies struct {
Amount float64 `bson:"amount" json:"amount"`
DaysBeforeCheckIn int `bson:"daysBeforeCheckIn" json:"daysBeforeCheckIn"`
}

cancelPolicyMain := Policies{}
cancelPolicy := RoomPolicies{}

if cancelAmount < 0 {
cancelPolicy.Amount = cancelAmount
cancelPolicy.DaysBeforeCheckIn = cancelDay
cancelPolicyMain.Policies = append(cancelPolicyMain.Policies, cancelPolicy)
}else{
cancelPolicyMain = agodaPolicies{}
cancelPolicyMain.Policies = append(cancelPolicyMain.Policies)
}

当数据出现时获得正确的数据结构。

"cancellationPolicy": {
"policies": [
{
"amount": 5141.58,
"daysBeforeCheckIn": 5
}
]
}

但是当数据不可用时获取空值结构。

"cancellationPolicy": {
"policies": null
}

我们需要带有空白数组 [] 的实际输出。

"cancellationPolicy": {
"policies": []
}

最佳答案

nil slice 值被编码为 JSON null 值。这记录在 json.Marshal() :

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.

nil 空 slice 被编码为空 JSON 数组。所以只需将 Policies.Policies 初始化为一个非 nil 的空 slice ,它就会在输出中为 []:

cancelPolicyMain = Policies{Policies: []RoomPolicies{}}

测试代码:

const cancelDay = 1

for cancelAmount := -500.0; cancelAmount <= 501; cancelAmount += 1000 {
cancelPolicyMain := Policies{}
cancelPolicy := RoomPolicies{}

if cancelAmount < 0 {
cancelPolicy.Amount = cancelAmount
cancelPolicy.DaysBeforeCheckIn = cancelDay
cancelPolicyMain.Policies = append(cancelPolicyMain.Policies, cancelPolicy)
} else {
cancelPolicyMain = Policies{Policies: []RoomPolicies{}}
cancelPolicyMain.Policies = append(cancelPolicyMain.Policies)
}

x := XmloutRoomRate{cancelPolicyMain}
if err := json.NewEncoder(os.Stdout).Encode(x); err != nil {
panic(err)
}
}

输出(在 Go Playground 上尝试):

{"cancellationPolicy":{"policies":[{"amount":-500,"daysBeforeCheckIn":1}]}}
{"cancellationPolicy":{"policies":[]}}

关于arrays - 使用 struct 在 Go 中处理空 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69663010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com