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

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

Handle optional JSON field in HTTP request body

问题

我有一个这样的结构体:

  1. type MyStruct struct {
  2. Name string `json:"name"`
  3. Age int `json:"age"`
  4. Email string `json:"email"`
  5. }

然后我有一些值(可以是默认值,这意味着我不需要更新这个值)作为HTTP请求数据进行传递。我注意到生成的JSON主体总是包含所有三个字段(nameageemail),即使我不需要更新它们中的所有字段。像这样:

  1. {
  2. "name":"Kevin",
  3. "age":10,
  4. "email":""
  5. }

有没有一种方法可以编组(Marshal)使得JSON主体不包含具有相同结构的所有字段?例如:

  1. {
  2. "name":"Kevin"
  3. }
英文:

I have a struct like this:

  1. type MyStruct struct {
  2. Name string `json:"name"`
  3. Age int `json:"age"`
  4. Email string `json:"email"`
  5. }

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:

  1. {
  2. "name":"Kevin",
  3. "age":10,
  4. "email":""
  5. }

Is there a way to Marshal so that the JSON body contains not all fields with the same struct? Example:

  1. {
  2. "name":"kevin"
  3. }

答案1

得分: 68

你想要使用omitempty选项。

  1. type MyStruct struct {
  2. Name string `json:"name,omitempty"`
  3. Age int `json:"age"`
  4. Email string `json:"email,omitempty"`
  5. }

如果你也想让Age是可选的,你需要使用指针,因为int的零值并不真正表示"空"。

  1. type MyStruct struct {
  2. Name string `json:"name,omitempty"`
  3. Age *int `json:"age,omitempty"`
  4. Email string `json:"email,omitempty"`
  5. }
英文:

You want to use the omitempty option

  1. type MyStruct struct {
  2. Name string `json:"name,omitempty"`
  3. Age int `json:"age"`
  4. Email string `json:"email,omitempty"`
  5. }

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"

  1. type MyStruct struct {
  2. Name string `json:"name,omitempty"`
  3. Age *int `json:"age,omitempty"`
  4. Email string `json:"email,omitempty"`
  5. }

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:

确定