Exchanging Json with server

VHi,

New go user here, please be gentle!!

I am considering redeveloping an existing java client application in go, but one aspect of doing so concerns me.

The application sends json to the server over a web socket, thats straightforward enough… but the responses could be any of up to ten or so different possibilities.

Here is the question. I know how to pass the response to a json unmarshaller method using a struct … and very well it works too… but as far as I can see only when you have a good idea about what the data contains,

The current java application just receives the response as a string and checks for the existence of certain strings (response codes) THEN based on the response code it unravels the json…how could this be done in go! Everything I’ve read so far suggests that you have to pass the response to a struct. How would I know which one?

Can I just work with the response body as a string first?

In an ideal world I would be able to check the message using jsonpath prior to indicating which struct to use in the unmarshal. Hope this makes sense.

Thanks

Check out this article - https://blog.gopheracademy.com/advent-2016/advanced-encoding-decoding/

Scroll down to the section on encoding and decoding generics. It should give you a few ideas of how to approach this in go. I’m the author of the post so happy to answer any follow-up questions if you have any after reading.

You can do the same with Go, read the body into a buffer, figure out final stricture you want to use, then decode from that buffer into the structure of you choice.

github.com/tidwall/gjson has a path syntax that allows you to extract some values from JSON data without unmarshaling the whole thing. It also recently got full marshaling/unmarshaling support.

I have also compiled lists of JSON packages and references if you would prefer something else.

1 Like

@joncalhoun

Thank you very much. That is a tremendous article and resource (bookmarked!). It has given me several ideas about how I could approach the situation. Amazing work!

@nathankerr

GJSON looks fantastic - what a brilliant piece of work! I’ll definitely be incorporating it into my projects. Thank you for pointing it out.

The more I get into Go the more I see fabulous contributions like GJSON and Gorilla for websockets.

Loving Go!

1 Like

My package GJP (https://github.com/tideland/golib/tree/master/gjp) is a generic JSON parser containing access by paths as well as diffs between two documents. Queries will follow.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.