解码时忽略空字段。

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

unmarshal ignore empty fields

问题

我从客户端收到一个JSON,在用户详细信息成功提交后。

JSON中的某些元素可以跳过,因为它们没有被更新。

在Go服务器端,我定义了一个等效的结构体。

服务器成功地将JSON字节解组为结构体。

type user struct {
    Id   *int64  `json:",omitempty"`
    Name *string `json:",omitempty"`
    Age  *int64  `json:",omitempty"`
}

但是对于未从客户端接收到的字段,默认情况下,解组会将字符串硬编码为nil,将字符串数组编码为空数组。

例如,如果我收到的JSON是{ "Id" : 64, "Name" : "Ryan" }
我不希望解组将其转换为{"Id" : 一些十六进制, "Name" : 一些十六进制, "Age" : nil}
为了简单起见,我希望它是{"Id" : 一些十六进制, "Name" : 一些十六进制 }

我该如何完全忽略该字段并映射我收到的内容?

Goplayground代码:http://play.golang.org/p/3dZq0nf68R

英文:

I get a JSON from a client on the successful submit of user details.

Some element in the JSON can be skipped since they were not updated.

On the Go server side, I have an equivalent struct defined.

The server successfully marshals the JSON bytes into the struct.

type user struct {
	Id       *int64  `json:",omitempty"`
	Name     *string `json:",omitempty"`
    Age      *int64  `json:",omitempty"`
}

But for fields which are not recieved from client, unmarshal by default hard-codes nil for string and empty array for string array.

For example, if I get the json { &quot;Id&quot; : 64, &quot;Name&quot; : &quot;Ryan&quot; }, <br/>
I don't want unmarshal to convert it to {&quot;Id&quot; : some hexadecimal, &quot;Name&quot; : some hexadecimal, &quot;Age&quot; : nil}. <br/>
To make it simple, I would expect it to be {&quot;Id&quot; : some hexadecimal, &quot;Name&quot; : some hexadecimal }

How can I totally ignore the field and map what I get?

Goplayground Code : http://play.golang.org/p/3dZq0nf68R

答案1

得分: 16

你有点困惑,fmt.Printf("%+v", animals) 打印的是 Go 的结构体,它会始终打印出所有指定的字段。

然而,如果你将其转换回 JSON,它将省略空字段。

请查看 http://play.golang.org/p/Q2M5oab2UX

英文:

You are a little bit confused, fmt.Printf(&quot;%+v&quot;, animals) prints the Go structs, which will always have all fields specified printed out.

However, if you convert it back to json, it will omit the nil fields.

Check http://play.golang.org/p/Q2M5oab2UX

huangapple
  • 本文由 发表于 2014年8月5日 08:02:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/25129345.html
匿名

发表评论

匿名网友

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

确定