unmarshal ignore empty fields

巧了我就是萌 提交于 2020-01-24 03:15:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!