Exclude struct field from json.Marshal

3,421 views
Skip to first unread message

Jev Björsell

unread,
Apr 3, 2013, 12:05:11 AM4/3/13
to golan...@googlegroups.com
Hello,

I'm using json.Marshal to convert a struct to Json, for the purpose of posting said json to a rest end point. 

The struct looks like this;
type Lead struct {
LeadNumber  string `json:"Lead_Number__c"`
FirstName   string
LastName    string
Company     string
Email       string
Description string
}

After the post, I get the same resource back in the response. 

I need to exclude the LeadNumber filed from the POST, as that field is read only, and assigned by the server. I want to read that same value back into my struct from the http.Response

How do I exclude a specific field from being converted when using json.Marshal? Keep in mind, I need to fill the field during json.Unmarshal.


Thanks!
-Jev 

Andrew Gerrand

unread,
Apr 3, 2013, 1:14:55 AM4/3/13
to Jev Björsell, golang-nuts
You'll need to create two structs, I believe.

Andrew


-Jev 

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Cem Ezberci

unread,
Apr 3, 2013, 1:20:29 AM4/3/13
to golan...@googlegroups.com
If my understanding is correct, when you marshal the struct, LeadNumber will be empty because you wouldn't be posting it with a value there since the server is supposed to assign it. However, response will come back with LeadNumber populated with a value assigned by the server. To achieve what you want, changing the json tag for LeadNumber to read `json:"Lead_Number__c,omitempty"` should work just fine.

-Cem

Jev Björsell

unread,
Apr 3, 2013, 11:09:01 AM4/3/13
to golan...@googlegroups.com
,omitempty is exactly what I was looking for, and works great. Thanks!
Reply all
Reply to author
Forward
0 new messages