3 ms·
I would say the most idiomatic way is having defined structs and using encoding/json. Even when you don't know the json schema in advance you can still parse it
by anonfunction 12y ago
I would say the most idiomatic way is having defined structs and using encoding/json. Even when you don't know the json schema in advance you can still parse it into an interface{}.
Here's an example: http://play.golang.org/p/jrqBcPuQei http://play.golang.org/p/jrqBcPuQei
- mrweasel 12y agoYou can parse JSON into an interface, but you end up doing tiresome casts if you structure is just somewhat nested.
- seletskiy 12y ago...or use very simple lib like this one [1] to access to deep-nested structs using one call. [1] https://github.com/zazab/zhash https://github.com/zazab/zhash
- Igglyboo 12y agoIt's definitely safer, but it's a living hell having to define a class for each possible json structure in Java with gson.
- anonfunction 12y agoNot sure where Java came into the conversation but I found a service[1] which I find really helpful for generating Golang structs from JSON. There is also a CLI tool[2] that does the same. [1]http://mholt.github.io/json-to-go/ http://mholt.github.io/json-to-go/ [2]https://github.com/ChimeraCoder/gojson https://github.com/ChimeraCoder/gojson
- eikenberry 12y agoAnother one. https://github.com/str1ngs/jflect https://github.com/str1ngs/jflect
- heavenlyhash 12y agoI use encoding/json for struct mapping when doing quick prototyping and simple applications. Parsing gets much more interesting when you start supporting many clients, broad version ranges of protocols. At that point, a little flexibility starts to be a godsend. This is just my personal experience, but so far, in every language where I've tried direct struct mappers, they become less and less helpful as your product gains a real user base and you have to start doing compatibility "in the wild". You can certainly do it with encoding/json and custom marshallers, but this library seems like it might be helpful. Protobufs have a lot of features that address this explicitly. I'm not a huge fan of protobufs (for a variety of off-topic reasons), but there's a great deal they got right: forcing consideration of backwards and forwards compatibility early is healthy for a project that's going to keep going for the long haul.