处理HTTP请求体中的可选JSON字段

huangapple go评论87阅读模式
英文:

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主体总是包含所有三个字段(nameageemail),即使我不需要更新它们中的所有字段。像这样:

{
  "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"`
}

huangapple
  • 本文由 发表于 2015年12月3日 05:54:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/34053815.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定