英文:
Handle optional JSON field in HTTP request body
问题
我有一个这样的结构体:
type MyStruct struct {
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email"`
}
然后我有一些值(可以是默认值,这意味着我不需要更新这个值)作为HTTP请求数据进行传递。我注意到生成的JSON主体总是包含所有三个字段(name
,age
和email
),即使我不需要更新它们中的所有字段。像这样:
{
"name":"Kevin",
"age":10,
"email":""
}
有没有一种方法可以编组(Marshal)使得JSON主体不包含具有相同结构的所有字段?例如:
{
"name":"Kevin"
}
英文:
I have a struct like this:
type MyStruct struct {
Name string `json:"name"`
Age int `json:"age"`
Email string `json:"email"`
}
Then I have some value (could be default, which means I do not need to update this value) to feed in as HTTP request data. I noticed the generated JSON body will always contains all three fields (name
, age
and email
), even if I don't need to update all of them. Like this:
{
"name":"Kevin",
"age":10,
"email":""
}
Is there a way to Marshal so that the JSON body contains not all fields with the same struct? Example:
{
"name":"kevin"
}
答案1
得分: 68
你想要使用omitempty
选项。
type MyStruct struct {
Name string `json:"name,omitempty"`
Age int `json:"age"`
Email string `json:"email,omitempty"`
}
如果你也想让Age
是可选的,你需要使用指针,因为int
的零值并不真正表示"空"。
type MyStruct struct {
Name string `json:"name,omitempty"`
Age *int `json:"age,omitempty"`
Email string `json:"email,omitempty"`
}
英文:
You want to use the omitempty
option
type MyStruct struct {
Name string `json:"name,omitempty"`
Age int `json:"age"`
Email string `json:"email,omitempty"`
}
If you want Age
to be optional as well you have to use a pointer, since the zero value of an int
isn't really "empty"
type MyStruct struct {
Name string `json:"name,omitempty"`
Age *int `json:"age,omitempty"`
Email string `json:"email,omitempty"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论