json murshal/unmarhsal struct that was got using custom interface type

71 views
Skip to first unread message

Viacheslav Biriukov

unread,
Aug 1, 2016, 1:07:07 PM8/1/16
to golang-nuts
Hi, 

I want to marshal/unmarshal object for saving in key/value storage. 
The question is: if I got this object using function, that accepts interface type, lets say for example: base.Pricer. And there are more than one type struct that satisfy this interface. I know while marshaling what type this object have (using reflection), and theoretically can save this type in storage. But when I try to load this object – I want to get exactly that type what was before serialization. But I don't know how to do this and is this is a good pattern?

Thank you.

nathan....@docker.com

unread,
Aug 1, 2016, 3:09:57 PM8/1/16
to golang-nuts
Viacheslav,

Your best bet here in my opinion is to have an intermediate object that contains type information which you Unmarshal into first to get the concrete type.  Then, you have a switch to Unmarshal the remainder of the object into the real deal.  We did a similar mechanic to this on Docker Machine at one point where the various Drivers would contain a string indicating which type they "actually" are.

Nathan

Viacheslav Biriukov

unread,
Aug 1, 2016, 6:35:33 PM8/1/16
to golang-nuts, nathan....@docker.com
Hi Nathan,

Thank you for reply. Yes I thought about this approach. But it looks  a little ugly. Every time you add new struct that can be used – you should  don't forget to update switch. But it seems that there is no other way.

Thank you!
Reply all
Reply to author
Forward
0 new messages