11
votes

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
I don't understand the question. If you get nil in the field it means the json did not have a value for it and unmarshall will set it the default 'zero' value for the type of the field. - fabrizioM
I dont want the feature of setting nil if json field didn't have the value. I want it to totally ignore the field if it is not present i.e. in other words, json contains only fields which have value. - Mydeveloperpal
I am pretty new to goLang, just wanted to find out if a feature like that is present. I don't understand what's the confusion here. - Mydeveloperpal
@Pals: Did you finally get an answer? The one that you have marked the answer is for Marshal, but you asked question for unmarshalling. - inquisitive

1 Answers

15
votes

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