英文:
Need to pass empty slice in [] this format and not as ""
问题
我有一个具有一个名为"body"的属性的API:
type Reg struct{
Env []string json:"env"
}
在调用API时,我需要将"env"的值作为可选参数传递。
即以这种格式 env: []
,而不是 env: ""
有人可以帮忙吗?
我尝试使用 len(env)==0,但它将""和[]都视为空值。
我还尝试使用 reflect.ValueOf(Reg.Env).Kind() == reflect.Slice 来区分""和[],但它将两个值都视为切片。
英文:
I have a api with one attribute of body as
type Reg struct{
Env []string json:"env"
}
while calling the api I need to pass value of "env" as optional parameter.
i.e.
in this format env: []
, and not as env: ""
Can anyone help pls.
I have tried using len(env)==0 but it take both "" and [] as empty.
I have also tried using reflect.ValueOf(Reg.Env).Kind() == reflect.Slice to differentiate between "" and [] but it takes both the values as slice only.
答案1
得分: 1
如果你检查json.Unmarshal
的错误,例如,你将会知道用户是否传递了无效的输入。
var r struct { Env []string `json:"env"` }
if err := json.Unmarshal([]byte(`{"env": ""}`), &r); err != nil {
fmt.Println(err)
}
会产生以下错误信息:
json: cannot unmarshal string into Go struct field .env of type []string
链接:https://go.dev/play/p/LozhJ14C7zj
当你使用解码器时,情况也是一样的。例如,从HTTP请求的主体中。
var r struct { Env []string `json:"env"` }
dec := json.NewDecoder(strings.NewReader(`{"env": ""}`))
if err := dec.Decode(&r); err != nil { fmt.Println(err) }
链接:https://go.dev/play/p/_XpY3jquxVx
英文:
If you check the error of json.Unmarshal
, for example, you will know if the user passed invalid input.
var r struct { Env []string `json:"env"` }
if err := json.Unmarshal([]byte(`{"env": ""}`), &r); err != nil {
fmt.Println(err)
}
Produces this error message:
json: cannot unmarshal string into Go struct field .env of type []string
https://go.dev/play/p/LozhJ14C7zj
The same happens when you use a decoder. I.e. from a http requests body.
var r struct { Env []string `json:"env"` }
dec := json.NewDecoder(strings.NewReader(`{"env": ""}`))
if err := dec.Decode(&r); err != nil { fmt.Println(err) }
答案2
得分: 0
根据您需要发送的内容,有多种选项:
情况A:
Reg{}
将被 JSON 序列化为 {"env": null}
情况B:
Reg{Env: []string{} }
将被 JSON 序列化为 {"env": []}
情况C:
如果在结构体标签中添加 ,omitempty
,如下所示:
type Reg struct {
Env []string `json:"env,omitempty"`
}
那么 Reg{}
将被 JSON 序列化为 {}
在这里可以查看代码示例:https://go.dev/play/p/lKI91VCoI0V
英文:
There are multiple options depending on what do you need to send:
Case A:
Reg{}
will be json-serialized to {"env": null}
Case B:
Reg{Env: []string{} }
will be json-serialized to {"env": []}
Case C:
If ,omitempty
is added to the struct tag like this:
type Reg struct {
Env []string `json:"env,omitempty"`
}
then Reg{}
will be json-serialized to {}
See code example here: https://go.dev/play/p/lKI91VCoI0V
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论