问题
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 { "Id" : 64, "Name" : "Ryan" }
,
I don't want unmarshal to convert it to {"Id" : some hexadecimal, "Name" : some hexadecimal, "Age" : nil}
.
To make it simple, I would expect it to be {"Id" : some hexadecimal, "Name" : some hexadecimal }
How can I totally ignore the field and map what I get?
Goplayground Code : http://play.golang.org/p/3dZq0nf68R
回答1:
You are a little bit confused, fmt.Printf("%+v", 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
来源:https://stackoverflow.com/questions/25129345/unmarshal-ignore-empty-fields