Thanks. I read that blog post earlier and presents two different ways of handling this. Each maintains a list of switch cases and constants respectively so still not entirely dynamic.
I'll probably just go with a switch then. On Wednesday, 28 March 2018 13:25:47 UTC+1, Andrei Tudor Călin wrote: > > It isn't really possible to do so because there is no nice and type safe > way of getting from a string in the JSON to a Go type, > and a value of said type. You must write a little bit of extra code. > > This article: http://eagain.net/articles/go-dynamic-json/ presents a good > approach. > > On Wednesday, March 28, 2018 at 1:46:24 PM UTC+2, > gary.wi...@victoriaplumb.com wrote: >> >> Is it possible to unmarshall Json by selecting the struct from a field in >> the Json? >> >> I'm porting some PHP code to Go and this is something I may have to >> approach differently. >> Here is the Json: >> >> [ >> { >> "class": "Domain\\Model\\Message", >> "skus": [ >> "FOO1" >> ], >> "label": "Lorem", >> "text": "Lorem ipsum dolor sit amet.", >> } >> ] >> >> In PHP the above Json is decoded into an associative array and I can use >> the 'class' field to decode further to an object (dynamically selecting the >> object using the 'class' value), like this: >> >> $obj = $decoded['class']::jsonDeserialize($decoded); >> >> >> assert($obj->label == "Lorem"); >> >> So the above really translates to calling the static method on a concrete >> class, like this: >> >> $obj = Domain\\Model\\Message::jsonDeserialize($decoded); >> >> Can I do anything similar in Go without using a switch defining separate >> unmarshalling for each class? >> >> -- 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+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.